<?php
	error_reporting(E_ALL || ~E_NOTICE);
//	error_reporting(E_ALL || ~E_DEPRECATED || ~E_STRICT || ~E_NOTICE || ~E_WARNING || ~E_CORE_WARNING);	
	
	$action = ""; //1---get   2---add   3---del   4----view
//	$table = $_GET["table"];
/*	$xiazaibiao = "";	
	if($xiazaibiao = $_POST["xiazaibiao"])
	{
		$xiazaibiao = $_POST["xiazaibiao"];
	}
	if($_GET['picfilename'])
	{
		$picfilename=$_GET['picfilename'];
	}else if($_POST['picfilename'])
	{
		$picfilename=$_POST['picfilename'];
	}*/
	
    if($_POST['action'])
	{
		$action = $_POST['action'];
	}
	else if($_GET['action'])
	{
		$action = $_GET['action'];
	}
	else if($_POST['dwjson'])
	{
		$dwjson = $_POST['dwjson'];
		$jsondata=json_decode($dwjson,true);
		$action=$jsondata["action"];
	}else
	{
		$data=file_get_contents('php://input');
//		var_dump($data);
		if($data)
		{		
			$jsondata=json_decode($data,true);
			$action=$jsondata["action"];
			if(!$action)
			{
				return;	
			}
		}else
		{
			return;
		}
	}

	file_put_contents("test.log", "data: ".$data." action: ".$action." line: ".__LINE__."\n", FILE_APPEND);		
    
	if($action == "dwau")
	{
		//将出错信息输出到一个文本文件
		ini_set('error_log', dirname(__FILE__) . '/test.log');
		//设置时区
		ini_set('date.timezone','Asia/Shanghai');
//		@file_put_contents("test.log", "action =".$action." LINE:".__LINE__."\n", FILE_APPEND);
		$myconn=dwopendb();
		if(!$myconn)
		{
//			@file_put_contents("test.log", "Could not connect db"." LINE:".__LINE__."\n", FILE_APPEND);
			return;
/*			$myconn=@mysql_connect("localhost","dw","DWdawu-309");
			if(!$myconn)
			{
//				die('Could not connect: '.mysql_error());
				$string = "Could not connect database: ".mysql_error()." LINE:".__LINE__."\n";
				file_put_contents("test.log", $string, FILE_APPEND);
				$response = base64_encode("{\"res\":\"deny3\"}");
				echo $response;
//				dwclosedb($myconn);
				return;
			}
			$db_selected=mysql_select_db("dwzuapairenlian",$myconn);
			if(!$db_selected)
			{        
				$strSql="CREATE DATABASE dwzuapairenlian;";
				$result=mysql_query($strSql,$myconn);
				if($result==false)
				{
					die("Can't use database dwaccessDB : ".mysql_error());
					$string = "Can't use database : ".mysql_error()." LINE:".__LINE__."\n";
					file_put_contents("test.log", $string, FILE_APPEND);
					dwclosedb($myconn);
					$response = base64_encode("{\"res\":\"deny3\"}");
					echo $response;					
					return;
				}
				$strSql="set character_set_database=utf8;";
				$result=mysql_query($strSql,$myconn);
			}*/
		}
		//初始化数据库	
//		$strSql="CREATE TABLE if not exists accessrecord(tkid integer PRIMARY KEY AUTO_INCREMENT,cardnum text, cardlen int default 26,controlerNum text,gatenum int default 0,entrance text,accessstat text,CreatedTime text,xjieguo int default 0,rljieguo int default 0,ajjieguo int default 0,gonghao text,busidu float(5,2) default 100.00 NOT NULL) DEFAULT CHARSET=utf8;";
		$strSql="CREATE TABLE if not exists accessrecord(tkid integer PRIMARY KEY AUTO_INCREMENT,cardnum text, cardlen int default 26,controlerNum text,gatenum int default 0,entrance text,accessstat text,CreatedTime text,xjieguo int default 0,rljieguo int default 0,ajjieguo int default 0,gonghao text,zhaneiyouren text) DEFAULT CHARSET=utf8;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		@mysql_free_result($result);
//		$strSql="create table if not exists gatesetting(skid integer PRIMARY KEY AUTO_INCREMENT,controlerNum text,IP text,PORT int,serverIP text,serverPORT int DEFAULT 80,tcpPORT int DEFAULT 1119, realtimepath text,Camera0ADDR text,Camera0PORT int DEFAULT 80,Camera0rtsp text,Camera1ADDR text,Camera1PORT int DEFAULT 80,Camera1rtsp text,Camera2ADDR text,Camera2PORT int DEFAULT 80,Camera2rtsp text,Camera3ADDR text,Camera3PORT int DEFAULT 80,Camera3rtsp text,jianquanfangshi text,sVersion text,lasttime text,gatenum text,gatename text,controlmethod text,delayopentime text,delayclosetime text,sensorstat text,readerfunction text,attendancecheck text,region text,password text,forcepass text,lianjie text,antipassback text) DEFAULT CHARSET=utf8;";
		$strSql="create table if not exists gatesetting(skid integer PRIMARY KEY AUTO_INCREMENT,controlerNum text,IP text,PORT int,serverIP text,serverPORT int DEFAULT 80,tcpPORT int DEFAULT 1119, realtimepath text,CameraADDR text,CameraPORT int DEFAULT 80,CameraRTSP text,jianquanfangshi text,sVersion text,lasttime text,gatenum text,gatename text,controlmethod text,delayopentime text,delayclosetime text,sensorstat text,readerfunction text,attendancecheck text,region text,password text,forcepass text,lianjie text,antipassback text) DEFAULT CHARSET=utf8;";
		$result=mysql_query($strSql,$myconn);
//		@mysql_free_result($result);
		$result=mysql_query($strSql);
//		$strSql="create table if not exists staffbasesetting(rowid integer not null PRIMARY KEY AUTO_INCREMENT,staffnum text not null,staffname text not null,signature text not null ,cardnum text not null,departmentname text not null,departmentID text not null,controlerNum text not null,gatenum text not null,periodofvalitystart text  not null,periodofvalityend text not null,jingruqishi1 text not null,jingrujieshu1 text not null,likaiqishi1 text not null,  likaijieshu1 text not null,jingruqishi2 text not null,jingrujieshu2 text not null,likaiqishi2 text not null,likaijieshu2 text not null,jingruqishi3 text not null,jingrujieshu3 text not null,likaiqishi3 text not null,likaijieshu3 text not null,jingruqishi4 text not null,jingrujieshu4 text not null,likaiqishi4 text not null,likaijieshu4 text not null,staffgender text not null,staffage int default 0 not null,picfilename text not null) DEFAULT CHARSET=utf8;";
		$strSql="create table if not exists staffbasesetting(rowid integer not null PRIMARY KEY AUTO_INCREMENT,staffnum text not null,staffname text not null,signature text not null ,cardnum text not null,departmentname text not null,departmentID text not null,controlerNum text not null,gatenum text not null,periodofvalitystart text  not null,periodofvalityend text not null,staffgender text not null,staffage int default 0 not null,picfilename text not null) DEFAULT CHARSET=utf8;"; 
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		@mysql_free_result($result);	
//		$strSql="create table if not exists cmdform(skid integer PRIMARY KEY AUTO_INCREMENT,controlerNum text,transid text,cmdstr text);";		
//		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$strSql="create table if not exists yinpinbiao(yinpinxuhao text,ypwjming text,shuoming text) DEFAULT CHARSET=utf8;";
    	$result=mysql_query($strSql,$myconn);
    	@mysql_free_result($result);
    	
    	$strSql="create table if not exists shipinbiao(shipinxuhao text,spwjming text,shuoming text) DEFAULT CHARSET=utf8;";
    	$result=mysql_query($strSql,$myconn);
		@mysql_free_result($result);
//		$strSql="create table if not exists serversetting(skid integer PRIMARY KEY AUTO_INCREMENT,controlerNum text,serverIP text,serverPORT int DEFAULT 80,tcpPORT int DEFAULT 1119, cmdresultpath text,realtimepath text,DetectDevicepath text,Camera0ADDR text,Camera0PORT int DEFAULT 80,Camera1ADDR text,Camera1PORT int DEFAULT 80,Camera2ADDR text,Camera2PORT int DEFAULT 80,Camera3ADDR text,Camera3PORT int DEFAULT 80,reQusttime int DEFAULT 15,sVersion text);";
//		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		@mysql_free_result($result);
		$strSql="select MAX(rowid) from staffbasesetting;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$RowCount=array();
		$RowCount = mysql_fetch_array($result);
		mysql_free_result($result);
		if(!$RowCount[0])
		{
//			$strSql="insert into staffbasesetting(staffnum,staffname,signature,cardnum,controlerNum, departmentname,departmentID,gatenum,staffgender,picfilename,periodofvalitystart,periodofvalityend,jingruqishi1,jingrujieshu1,likaiqishi1,likaijieshu1,jingruqishi2,jingrujieshu2,likaiqishi2,likaijieshu2,jingruqishi3,jingrujieshu3,likaiqishi3,likaijieshu3,jingruqishi4,jingrujieshu4,likaiqishi4,likaijieshu4) values('1','admin', 'e10adc3949ba59abbe56e057f20f883e','1','ALL','hr','1','all','nan','wu','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59','2018-01-01 00:00:00','2028-01-01 23:59:59');";	
			$strSql="insert into staffbasesetting(staffnum,staffname,signature,cardnum,controlerNum, departmentname,departmentID,gatenum,staffgender,picfilename,periodofvalitystart,periodofvalityend) values('1','admin', 'e10adc3949ba59abbe56e057f20f883e','1','ALL','hr','1','all','nan','wu','2018-01-01 00:00:00','2028-01-01 23:59:59');";
//			$result=mysql_query($strSql,$myconn);
			$result=mysql_query($strSql);
			@mysql_free_result($result);
		}
/*		$strSql="SELECT MAX(skid) FROM serversetting;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$dbResult = mysql_fetch_array($result);
		mysql_free_result($result);
		if(!$dbResult[0])
		{
			$strSql="INSERT INTO serversetting(serverIP,serverPORT,cmdresultpath,realtimepath,DetectDevicepath,Camera0ADDR,Camera0PORT,Camera1ADDR,Camera1PORT,Camera2ADDR,Camera2PORT,Camera3ADDR,Camera3PORT,reQusttime,sVersion) VALUES('10.10.10.239','80','/cmdresult.php','/realtime.php','/_DetectDevice.php','10.10.10.143','80','10.10.10.143','80','10.10.10.143','80','10.10.10.143','80','15','2017V08.09R');";
//			$result=mysql_query($strSql,$myconn);
			$result=mysql_query($strSql);
		}
		mysql_free_result($result);
		$strSql="UPDATE serversetting SET sVersion = '2018V01.12P2P_YZK'; ";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		mysql_free_result($result);*/
		$strSql="SELECT MAX(skid) FROM gatesetting;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$dbResult = mysql_fetch_array($result);
		mysql_free_result($result);
		if(!$dbResult[0])
		{
			for($i=0;$i<4;$i++)
			{
//				$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,region,controlmethod,delayopentime, delayclosetime,sensorstat,readerfunction,attendancecheck,password,forcepass,antipassback,serverIP,serverPORT,cmdresultpath,realtimepath,DetectDevicepath,Camera0ADDR,Camera0PORT,Camera1ADDR,Camera1PORT,Camera2ADDR,Camera2PORT,Camera3ADDR,Camera3PORT,reQusttime,sVersion) VALUES('ALL','$i','大门','总部','card','0','0','NG','26','yes', '123456','999999','no','10.10.10.239','80','/cmdresult.php','/realtime.php','/_DetectDevice.php','10.10.10.143','80','10.10.10.143','80','10.10.10.143','80','10.10.10.143','80','15','2017V08.09R');";
//				$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,region,controlmethod,delayopentime, delayclosetime,sensorstat,readerfunction,attendancecheck,password,forcepass,antipassback,serverIP,serverPORT,realtimepath,Camera0ADDR,Camera0PORT,Camera0rtsp,Camera1ADDR,Camera1PORT,Camera1rtsp,Camera2ADDR,Camera2PORT,Camera2rtsp,Camera3ADDR,Camera3PORT,Camera3rtsp,jianquanfangshi,sVersion,IP,PORT,lianjie,lasttime) VALUES('ALL','$i','大门','总部','card','0','0','NG','26','yes', '123456','999999','no','10.10.10.239','80','/dwrealtime.php','127.0.0.1','80','rtsp://admin:DAWU201506@192.168.2.64:554//Streaming/Channels/1','127.0.0.1','80','rtsp://admin:DAWU201506@192.168.2.108:554/cam/realmonitor?channel=1&subtype=0','127.0.0.1','80','rtsp://admin:DAWU201506@192.168.2.64:554//Streaming/Channels/1','127.0.0.1','80','rtsp://admin:DAWU201506@192.168.2.108:554/cam/realmonitor?channel=1&subtype=0','jizhong','2018V11.28P2P_fxc','127.0.0.1','80','offline','2016-01-01 00:00:00');";
				$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,region,controlmethod,delayopentime, delayclosetime,sensorstat,readerfunction,attendancecheck,password,forcepass,antipassback,serverIP,serverPORT,realtimepath,CameraADDR,CameraPORT,CameraRTSP,jianquanfangshi,sVersion,IP,PORT,lianjie,lasttime) VALUES('ALL','$i','大门','总部','card','0','0','NG','26','yes', '123456','999999','no','127.0.0.1','80','/dwrealtime.php','127.0.0.1','80','127.0.0.1','jizhong','2018V11.28P2P_fxc','127.0.0.1','80','offline','2016-01-01 00:00:00');";

				$result=mysql_query($strSql,$myconn);
			}
		}
		mysql_free_result($result);
/*		$strSql="UPDATE gatesetting SET sVersion = '2018V11.28P2P_fxc'; ";
		$result=mysql_query($strSql,$myconn);
		mysql_free_result($result);*/
		$auth=$jsondata["audata"];
		
		//输出解码后的内容
		$authDc = base64_decode($auth);
//		@file_put_contents("test.log", "authDc: ".$authDc." LINE:".__LINE__."\n", FILE_APPEND);
		$authArr=json_decode($authDc,true);
//		@file_put_contents("test.log", "authArr: ".$authArr." LINE:".__LINE__."\n", FILE_APPEND);
		//解析比对用户名、密码并返回结果
		if(!strstr($authDc,"\"username\":\""))
		{
			dwclosedb($myconn);
			$response = base64_encode("{\"res\":\"deny5\"}");
			echo $response;			
			return;
//			@file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND);
		}
//		else 
//		{
		$index1 = substr($authDc,13);
//		file_put_contents("test.log", "index1 =".$index1." LINE:".__LINE__."\n", FILE_APPEND);
		$index2 = strpos($index1,"\"");
//		file_put_contents("test.log", "index2 =".$index2." LINE:".__LINE__."\n", FILE_APPEND);
		if($index2==0)
		{
			dwclosedb($myconn);
			$response = base64_encode("{\"res\":\"deny3\"}");
			echo $response;
//			dwclosedb($myconn);
			return;
//		    file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND); 
		}else if($index2>24)
		{
			dwclosedb($myconn);
			$response = base64_encode("{\"res\":\"deny6\"}");
			echo $response;
//		    file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND);
//			dwclosedb($myconn);
			return;
		}else
		{
			$auNameLen = $index2;
			$auName = substr($authDc,13,$index2);
//			file_put_contents("test.log", "auName =".$auName."  auNameLen =".$auNameLen." LINE:".__LINE__."\n", FILE_APPEND);
			if(!strstr($authDc,"\"password\":\""))
			{
				dwclosedb($myconn);
				$response = base64_encode("\"res\":\"deny5\"}");
				echo $response;
//		        file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND);
//				dwclosedb($myconn);
				return;
			}else
			{
				$index1 = strstr($authDc,"\"password\":\"");
				$index2 = substr($index1,12);
				$index3 = strpos($index2,"\"");
//		        file_put_contents("test.log", "  index1=".$index1."  index2=".$index2."  index3=".$index3." LINE:".__LINE__."\n", FILE_APPEND);
				if($index3==0)
				{
					dwclosedb($myconn);
					$response = base64_encode("{\"res\":\"deny4\"}");
					echo $response;
//		            file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND);
//					dwclosedb($myconn);
					return;
				}else if($index3>48)
				{
					dwclosedb($myconn);
					$response = base64_encode("{\"res\":\"deny6\"}");
					echo $response;
//		            file_put_contents("test.log", "response =".$response." LINE:".__LINE__."\n", FILE_APPEND); 
//					dwclosedb();
					return;
				}
				$auSignLen = $index3;
				$auSign = substr($index1,12,$index3);				
			}
		}
		if($authArr["type"]==="login")
		{
			$strSql = "select distinct staffname,signature from staffbasesetting where staffname=\"".$auName."\";";
//			file_put_contents("test.log", "strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND); 
	//用mysql_query函数从staffbasesetting表里读取数据
			$result=mysql_query($strSql,$myconn);
//			$result=mysql_query($strSql);
	//通过循环读取数据内容	
			$auRE = array();
			$auRE = mysql_fetch_array($result);
//			while($row=mysql_fetch_array($result))
//			{
//				$auRE = $row;
//				file_put_contents("test.log", "  auRE[0] =".$auRE[0]."  auRE[1] =".$auRE[1]."  auRE[2] =".$auRE[2]."\n", FILE_APPEND); 
//			}	
	//	    print_r(mysql_fetch_array($result));
	//释放资源
			mysql_free_result($result);
	//		file_put_contents("test.log", "  156auRE[0]: ".$auRE[0]."  156auRE[1]: ".$auRE[1], FILE_APPEND);
			if(!$auRE[0])
			{
				$response = base64_encode("{\"res\":\"deny1\"}");
				echo $response;
//			    file_put_contents("test.log", "  response160: deny1 ".$response." LINE:".__LINE__."\n", FILE_APPEND); 
			}else 
			{
				if($auRE[1]==$auSign)
				{
//					$response = base64_encode("{\"res\":\"success\",\"authstat\":\"".$auRE[2]."\"}");
					$response = base64_encode("{\"res\":\"success\",\"authstat\":\"3\"}");
					echo $response;
//			        file_put_contents("test.log", "  authstat: 3  LINE:".__LINE__."\n", FILE_APPEND);
					$strSql="UPDATE gatesetting SET lianjie= 'offline';";
					$result=mysql_query($strSql,$myconn);				
				}else
				{
					$response = base64_encode("{\"res\":\"deny2\"}");
					echo $response;
//			        file_put_contents("test.log", "  response172: deny2 ".$response." LINE:".__LINE__."\n", FILE_APPEND);
				}
			}
		}else if($authArr["type"]==="regist")
		{
			$strSql = "select distinct staffname from staffbasesetting where staffname=\"".$auName."\";";
			$result=mysql_query($strSql,$myconn);
//			$result=mysql_query($strSql);
			$auRE1=mysql_fetch_array($result);
			if($auRE1[0])
			{
				$response = base64_encode("{\"res\":\"deny7\"}");
				echo $response;
			}else
			{
				$strSql = "INSERT INTO staffbasesetting(staffname,signature) VALUES('".$auName."','".$auSign."');";
				$result1=mysql_query($strSql,$myconn);
//				$result=mysql_query($strSql);
				mysql_free_result($result1);
				$response = base64_encode("{\"res\":\"success\"}");
				echo $response;	
			}
			mysql_free_result($result);
		}
//		}
		dwclosedb($myconn);
	}
	
	if($action=="dwquyinpinbiao")
	{		
//		snprintf(sqlstr,255,"select yinpinxuhao,ypwjming,shuoming from yinpinbiao ORDER BY rowid DESC limit %d,%d;",pagestart,pageend);

	}

	if($action=="dwxieyinpinbiao")
	{
		
	}
	
	if($action=="dwxiafawenjian")
	{
//		file_put_contents("test.log", "action:".$action."\n", FILE_APPEND);
		if($_FILES["filename"]["error"] > 0)
		{
			$echostr = "Error: " . $_FILES["filename"]["error"] . "<br />";
			file_put_contents("test.log", "$echostr\n", FILE_APPEND);
	//		echo "<script language=\"JavaScript\">alert('$echostr');</script><br/>";
	//        echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/serversetting.php',5000);</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',5000);</script><br/>";	
			return;
		}else if (file_exists("upload/".$_FILES["filename"]["name"]))
		{
			$echostr = $_FILES["filename"]["name"] . " 已经存在. ";
			file_put_contents("test.log", "$echostr\n", FILE_APPEND);
			echo "<script language=\"JavaScript\">alert('$echostr');</script><br/>";
	//		echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/serversetting.php',500);</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";
			return;
		}
		else
		{        
			$fname=basename($_FILES["filename"]["name"]);
			move_uploaded_file($_FILES["filename"]["tmp_name"],"upload/".$fname);
			$echostr = "提交成功,开始下发。文件保存在：" . "upload/".$fname;
			echo "<script language=\"JavaScript\">alert('$echostr');</script><br/>";
	//		echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/serversetting.php',5000);</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',5000);</script><br/>";			
		}
		if($_POST['controlernum'])
		{
			$controlernum = $_POST['controlernum'];
	//		echo "<script language=\"JavaScript\">alert('3...'+'$controlernum');</script><br/>";
		}
		$myconn=dwopendb();
		
/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
		$result44=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$dbResult44 = mysql_fetch_array($result44);
		if($dbResult44[0])
		{
			$TCPport = $dbResult44[0];
		}else
		{
			$TCPport = "1119";
		}
		mysql_free_result($result44);*/
		$exec="SELECT serverIP,serverPORT FROM serversetting;"; 
		$result=mysql_query($exec); 
		if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1)) 
		{ 
			mysql_free_result($result);
			mysql_close($myconn);
			$string = "Can't exec database : ".mysql_error();
			file_put_contents("test.log", $string, FILE_APPEND);
	//		echo "fail";
			exit; 
		}
		$item = mysql_fetch_row($result);
		mysql_free_result($result);
		
		if($controlernum==="ALL")
		{
			$strSql="SELECT DISTINCT controlernum FROM gatesetting ORDER BY lasttime DESC;";
			$result=mysql_query($strSql,$myconn);
//			$result=mysql_query($strSql);
			while($dbResult = mysql_fetch_row($result))
			{
				$transid=uuid();
				$cmdstr="{\"dwdevice\":\"". $dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_APPUPGRADE\",\"url\":\"http://$item[0]:$item[1]/dwDownLoadfile.php?key=$fname\"}";
				dwsendtoserver($cmdstr,$myconn);
			}
			mysql_free_result($result);
		}else
		{
			$transid=uuid();
			$cmdstr="{\"dwdevice\":\"". $controlerNum."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_APPUPGRADE\",\"url\":\"http://$item[0]:$item[1]/dwDownLoadfile.php?key=$fname\"}";
			dwsendtoserver($cmdstr,$myconn);
		}		
		dwclosedb($myconn);		
	}
	
	if($action=="accessrecord")
	{
/*		if($jsondata["table"])
		{
			$table = $jsondata["table"];
		}*/
//		$table = $_GET["table"];
//		$_POST['action']
//		$table = $_POST["table"];
		$table = $action;
//		@file_put_contents("test.log", "table: ".$table."\n", FILE_APPEND);
		$exportStr = "";

//		$headerArr = array("accessrecord"=>"序号,卡号,位数,设备号,闸号,是否在内,是否放行,刷卡时间\n","attendanceform"=>"skid,staffnum,staffname,departmentname,latetimes,earlytimes,overtimes,absentofwork,offtimes\n");
		$headerArr = array("accessrecord"=>"tkid,cardnum,cardlen,controlerNum,gatenum,zainei,tongguo,CreatedTime\n","attendanceform"=>"skid,staffnum,staffname,departmentname,latetimes,earlytimes,overtimes,absentofwork,offtimes\n");
		$myconn=dwopendb();
//		$filename = "table.csv";
		$temp =  "fields terminated by ',' optionally enclosed by '\"' lines";
		$strSql="select * from $table";
		$result=mysql_query($strSql,$myconn);
		while($rowsnum = mysql_fetch_array($result,MYSQL_NUM))
		{
			//var_dump($rowsnum);
			foreach ($rowsnum as $key => $value) 
			{
				$temp = iconv('GBK', 'utf-8', $value);
				if($key == count($rowsnum)-1)
				{
					//die("11 : ".$value);
					$exportStr = $exportStr . $temp . "\n";
				}
				else
				{
					$exportStr = $exportStr . $temp . ",";
				}				
			}
		}
		mysql_free_result($result);
		mysql_close($myconn);
		$file_name = $table . '.csv';
//		header("Content-Type: application/vnd.ms-excel; charset=GB2312");
		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
		header("Content-Disposition:attachment;filename=" . $file_name);
//		echo "<head><Content-Type: application/vnd.ms-excel; charset=GB2312> <Content-Disposition:attachment;filename=\"" . $file_name."\"> </head>";
		echo $headerArr[$table];
//		@file_put_contents("test.log", "headerArr: ".$headerArr[$table]."\n", FILE_APPEND);
		echo $exportStr;
//		@file_put_contents("test.log", "exportStr: ".$exportStr."\n", FILE_APPEND);		
	}

	if($action=="staffbasesetting")
	{
/*		if($jsondata["table"])
		{
			$table = $jsondata["table"];
		}*/
//		$table = $_GET["table"];
//		$_POST['action']
//		$table = $_POST["table"];
		$table = $action;
//		@file_put_contents("test.log", "table: ".$table."\n", FILE_APPEND);
		$exportStr = "";

//		$headerArr = array("accessrecord"=>"序号,卡号,位数,设备号,闸号,是否在内,是否放行,刷卡时间\n","attendanceform"=>"skid,staffnum,staffname,departmentname,latetimes,earlytimes,overtimes,absentofwork,offtimes\n");
//		$headerArr = array("accessrecord"=>"tkid,cardnum,cardlen,controlerNum,gatenum,zainei,tongguo,CreatedTime\n","attendanceform"=>"skid,staffnum,staffname,departmentname,latetimes,earlytimes,overtimes,absentofwork,offtimes\n","staffbasesetting"=>"rowid,staffnum,staffname,signature,cardnum,controlerNum, departmentname,departmentID,gatenum,periodofvalitystart,periodofvalityend,jingruqishi1,jingrujieshu1,likaiqishi1,likaijieshu1,jingruqishi2,jingrujieshu2,likaiqishi2,likaijieshu2,jingruqishi3,jingrujieshu3,likaiqishi3,likaijieshu3,jingruqishi4,jingrujieshu4,likaiqishi4,likaijieshu4,staffgender,staffage,picfilename\n");
		$headerArr = array("accessrecord"=>"tkid,cardnum,cardlen,controlerNum,gatenum,zainei,tongguo,CreatedTime\n","attendanceform"=>"skid,staffnum,staffname,departmentname,latetimes,earlytimes,overtimes,absentofwork,offtimes\n","staffbasesetting"=>"rowid,staffnum,staffname,signature,cardnum,controlerNum, departmentname,departmentID,gatenum,periodofvalitystart,periodofvalityend,staffgender,staffage,picfilename\n");
		$myconn=dwopendb();
//		$filename = "table.csv";
		$temp =  "fields terminated by ',' optionally enclosed by '\"' lines";
		$strSql="select * from $table";
		$result=mysql_query($strSql,$myconn);
		while($rowsnum = mysql_fetch_array($result,MYSQL_NUM))
		{
			//var_dump($rowsnum);
			foreach ($rowsnum as $key => $value) 
			{
				$temp = iconv('GBK', 'utf-8', $value);
				if($key == count($rowsnum)-1)
				{
					//die("11 : ".$value);
					$exportStr = $exportStr . $temp . "\n";
				}
				else
				{
					$exportStr = $exportStr . $temp . ",";
				}				
			}
		}
		mysql_free_result($result);
		mysql_close($myconn);
		$file_name = $table . '.csv';
//		header("Content-Type: application/vnd.ms-excel; charset=GB2312");
		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
		header("Content-Disposition:attachment;filename=" . $file_name);
//		echo "<head><Content-Type: application/vnd.ms-excel; charset=GB2312> <Content-Disposition:attachment;filename=\"" . $file_name."\"> </head>";
		echo $headerArr[$table];
//		@file_put_contents("test.log", "headerArr: ".$headerArr[$table]."\n", FILE_APPEND);
		echo $exportStr;
//		@file_put_contents("test.log", "exportStr: ".$exportStr."\n", FILE_APPEND);		
	}	
		
	if($action == "eraseDevice")
	{
		if($jsondata["controlerNum"])
		{
			$controlerNum = $jsondata["controlerNum"];
		}
		$myconn=dwopendb();
		$transid=uuid();
		$cmdstr="{\"dwdevice\":\"". $controlerNum."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_INIT\"}";					
		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
		$result44=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
/*		$dbResult44 = mysql_fetch_array($result44);
		if($dbResult44[0])
		{
			$TCPport = $dbResult44[0];
		}else
		{
			$TCPport = "1119";
		}
		mysql_free_result($result44);*/		
		dwsendtoserver($cmdstr,$myconn);
		dwclosedb($myconn);
		
//			$response = base64_encode("{\"res\":\"deny1\"}");
	
			$response = base64_encode("{\"res\":\"success\"}"); 
		
		echo $response;
	}
	
	if($action == "deleteDevice")
	{
		if($jsondata["controlerNum"])
		{
			$controlerNum = $jsondata["controlerNum"];
		}
		$myconn=dwopendb();
		$strSql = "DELETE from gatesetting where controlerNum=\"".$controlerNum."\";";
		$result=mysql_query($strSql,$myconn);
		if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1)) 
		{ 
			$response = base64_encode("{\"res\":\"deny1\"}");
		} 
		else
		{ 
			$response = base64_encode("{\"res\":\"success\"}"); 
		}		
		mysql_free_result($result);
		dwclosedb($myconn);
		echo $response;
	}
	
	if($action == "dwgetcontroler")
	{
		$controlerpagenum = 1;
		$pagestart=1;
		$pageend=1;
		$i=1;
		$j=1;   
		$s='';
		$strSql='';
		$accesstab='';
		$blank=false;
		$dbResult=array();
		$rowsnum=array();
//		$controlerpagenum=$jsondata["page"];
//		if($_POST['page'])
		if($jsondata["page"])
		{
			$controlerpagenum = (int)$jsondata["page"];
		}
		else
		{
			$controlerpagenum = 1;
		}
		$myconn=dwopendb();
		$strSql="select COUNT(*) from gatesetting WHERE controlerNum!='ALL';";
		$result=mysql_query($strSql,$myconn);	        
	    $rowsnum = mysql_fetch_array($result);
//        @file_put_contents("test.log", "rowsnum[0]:".$rowsnum[0]."\n", FILE_APPEND);
		$rowsnum[0] = ($rowsnum[0]/4);
        if($rowsnum[0]==0)
	    {
	        $blank = true;
	    }
		$pagemax=1;
		$pagemax = (($rowsnum[0]/5.0)-(int)($rowsnum[0]/5.0))>0.?(int)($rowsnum[0]/5.0)+1:(int)($rowsnum[0]/5.0);
		if($pagemax<1) $pagemax=1;

		if($controlerpagenum>$pagemax) $controlerpagenum=$pagemax;
		if($controlerpagenum<1) $controlerpagenum=1;
		$pagestart=5*$controlerpagenum-5;
		$pageend=5;
	    //如果请求的当前页是最后一页，则返回的条目数取余数，否则固定为5；
		if($controlerpagenum == $pagemax)
		{
			if(($rowsnum[0]%5)==0)
			{
				$rowsnum[0] = 5;
			}else
			{
				$rowsnum[0] = $rowsnum[0]%5;
			}
		}
		else
		{
			$rowsnum[0] = 5;
		}		
		$strSql="select DISTINCT controlerNum,IP,PORT,lasttime,lianjie from gatesetting WHERE controlerNum!='ALL' ORDER BY lasttime desc limit ".$pagestart.','.$pageend.';';
	//        file_put_contents("test.log", "strSql =".$strSql, FILE_APPEND);
		$result=mysql_query($strSql,$myconn);		
	//	    @file_put_contents("test.log", "rowsnum[0] =".$rowsnum[0], FILE_APPEND);	    
	//		for(i=1;i<=$rowsnum[0];i++)
		while($dbResult = mysql_fetch_array($result))
		{	        
			for($j=1;$j<=5;$j++)
			{			   
				if($i==1 && $j==1)
				{			        
					$accesstab = "{\"nrows\":\"".$rowsnum[0]."\",\"ncols\":\"5\",\"pageMaxium\":\"".$pagemax."\",\"controlerpagenum\":\"".$controlerpagenum."\",\"s0".$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'"';						
				}else
				{
					$accesstab = $accesstab.",\"s0".$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'"';
				}
			}
			$i++;			
		}
	//    }		
		if(!$blank)
		{
			$accesstab = $accesstab."}";
		}
		else
		{
			$accesstab = "{\"nrows\":\"0\",\"ncols\":\"5\",\"pageMaxium\":\"0\",\"controlerpagenum\":\"0\"}";
		}
		mysql_free_result($result);
		dwclosedb($myconn);	
		echo $accesstab;
	}
	
	if($action == "dwgetaccessrecord")
	{
		$controlerpagenum = 1;
		$pagestart=1;
		$pageend=1;
		$i=1;
		$j=1;   
		$s='';
		$sqlstr='';
//		$blank=false;
		$accesstab='{';
		$dbResult=array();
		$rowsnum=array();
//		if($_POST['page'])
		if($jsondata["page"])
		{
			$controlerpagenum = (int)$jsondata["page"];
//			$controlerpagenum = $_POST['page'];
		}
		else
		{
			$controlerpagenum = 1;
		}
//		file_put_contents("test.log", "controlerpagenum: ".$controlerpagenum, FILE_APPEND);
		$myconn=dwopendb();
		$strSql="select COUNT(*) from accessrecord;";
		$result=mysql_query($strSql,$myconn);	        
		$rowsnum = mysql_fetch_array($result);
//	        @file_put_contents("test.log", "rowsnum[0]:".$rowsnum[0]."\n", FILE_APPEND);
/*		if($rowsnum[0]==0)
		{
			$blank = true;
		}*/
		mysql_free_result($result);
		$pagemax=1;
		$pagemax = (($rowsnum[0]/10.0)-(int)($rowsnum[0]/10.0))>0.?(int)($rowsnum[0]/10.0)+1:(int)($rowsnum[0]/10.0);
		if($pagemax<1) $pagemax=1;
//		$string = "pagemax=".$pagemax."\n";
	//	    file_put_contents("test.log", $string, FILE_APPEND);
		if($controlerpagenum>$pagemax) $controlerpagenum=$pagemax;
		$pagestart=10*$controlerpagenum-10;
		$pageend=10;

		//如果请求的当前页是最后一页，则返回的条目数取余数，否则固定为10；
		if($controlerpagenum == $pagemax)
		{
			if(($rowsnum[0]%10)==0)
			{
				$rowsnum[0] = 10;
			}else
			{
				$rowsnum[0] = $rowsnum[0]%10;
			}
		}
		else
		{
			$rowsnum[0] = 10;
		}

		$strSql="select tkid,cardnum,gatenum,controlerNum,CreatedTime,accessstat,entrance from accessrecord ORDER BY tkid DESC limit ".$pagestart.','.$pageend.';';
	//        file_put_contents("test.log", "strSql =".$strSql, FILE_APPEND);
		$result=mysql_query($strSql,$myconn);		
	//	    @file_put_contents("test.log", "rowsnum[0] =".$rowsnum[0], FILE_APPEND);	    

		while($dbResult = mysql_fetch_array($result))
		{	        
			for($j=1;$j<=7;$j++)
			{			   
				$accesstab = $accesstab."\"s0".$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'",';
			}
			$i++;			
		}
		$i-=1;
		$accesstab = $accesstab."\"nrows\":\"$i\",\"ncols\":\"7\",\"pageMaxium\":\"$pagemax\",\"controlerpagenum\":\"$controlerpagenum\"}";	
//		file_put_contents("test.log", "accesstab :".$accesstab."\n", FILE_APPEND);
		mysql_free_result($result);
		dwclosedb($myconn);	
		echo $accesstab;		
	}
	
	if($action == "dwviewaccessdetail")
	{
		$myconn=dwopendb();
		$sqlstr="SELECT MAX(CreatedTime) FROM accessrecord WHERE accessstat = 'pass';";
		$result=mysql_query($sqlstr); 
		$accessitem = mysql_fetch_row($result);
		mysql_free_result($result);		
//		file_put_contents("test.log", "sqlstr :".$sqlstr."\n", FILE_APPEND);
		$sqlstr="SELECT cardnum,controlerNum,gatenum,tkid FROM accessrecord WHERE CreatedTime = '".$accessitem[0]."';";
		$result=mysql_query($sqlstr); 
		$accessitem1 = mysql_fetch_row($result);
		$sqlstr="select staffname,departmentname from staffbasesetting where cardnum='".$accessitem1[0]."'AND controlerNum='".$accessitem1[1]."' AND (gatenum='".$accessitem1[2]."' OR gatenum='all');";
		$result=mysql_query($sqlstr); 
		$staffitem = mysql_fetch_row($result);
		mysql_free_result($result);
//		file_put_contents("test.log", "sqlstr :".$sqlstr."\n", FILE_APPEND);
		$todaystart = strftime('%Y-%m-%d',strtotime($accessitem[0]))." 00:00:00";
		$todayend = strftime('%Y-%m-%d',strtotime($accessitem[0]))." 23:59:59";
		$sqlstr="SELECT COUNT(*) FROM accessrecord WHERE accessstat='pass' AND entrance='in' AND CreatedTime BETWEEN '".$todaystart."' AND '".$todayend."';";
		$result=mysql_query($sqlstr); 
		$todayinitem = mysql_fetch_row($result);
		mysql_free_result($result);
//		file_put_contents("test.log", "sqlstr :".$sqlstr."\n", FILE_APPEND);
		$sqlstr="SELECT COUNT(*) tkid FROM accessrecord WHERE accessstat='pass' AND entrance='out' AND CreatedTime BETWEEN '".$todaystart."' AND '".$todayend."';";
		$result=mysql_query($sqlstr); 
		$todayoutitem = mysql_fetch_row($result);
		mysql_free_result($result);
//		file_put_contents("test.log", "sqlstr :".$sqlstr."\n", FILE_APPEND);
//		$targetPath = dirname(__FILE__). "\\pictures\\";
//		$targetFile =$accessitem1[3].".jpg";
		$echostr = "{\"staffname\":\"".$staffitem[0]."\",\"departmentname\":\"".$staffitem[1]."\",\"cardnum\":\"".$accessitem1[0]."\",\"controlerNum\":\"".$accessitem1[1]."\",\"gatenum\":\"".$accessitem1[2]."\",\"CreatedTime\":\"".$accessitem[0]."\",\"todayin\":\"".$todayinitem[0]."\",\"todayout\":\"".$todayoutitem[0]."\",\"picfilename\":\"".$accessitem1[3]."\"}";
//		$echostr = "{\"staffname\":\"".$staffitem[0]."\",\"departmentname\":\"".$staffitem[1]."\",\"cardnum\":\"".$accessitem1[0]."\",\"controlerNum\":\"".$accessitem1[1]."\",\"gatenum\":\"".$accessitem1[2]."\",\"CreatedTime\":\"".$accessitem[0]."\",\"todayin\":\"".$todayinitem[0]."\",\"todayout\":\"".$todayoutitem[0]."\"}";
		dwclosedb($myconn);
		echo base64_encode($echostr);
	}
	
	if($action == "dwgetadmin")
	{
		$controlerpagenum = 1;
		$adminpagenum=$jsondata["adminpagenum"]; 
		if($adminpagenum=='adminpagenum')
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
//		dwtest();
		dwget($controlerpagenum,3,3,"s0");
	}
	if($action == "dwgetadmin_2")
	{
		$controlerpagenum = 1;
		$adminpagenum=$jsondata["adminpagenum"]; 
		if($adminpagenum=='adminpagenum')
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
//		dwtest();
		dwget($controlerpagenum,2,3,"s0");
	}
	if($action == "dwgetadmin_1")
	{
		$controlerpagenum = 1;
		$adminpagenum=$jsondata["adminpagenum"]; 
		if($adminpagenum=='adminpagenum')
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
//		dwtest();
		dwget($controlerpagenum,1,3,"s0");
	}
	if($action == "dwgetauth")
	{
		$authpagenum=$jsondata["authpagenum"]; 
		$controlerpagenum = 1;
		if($authpagenum=='authpagenum')
		{
			$controlerpagenum = $authpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
		dwget($controlerpagenum,4,10,"s50");
	}
	
	if($action =="dwdelauth")
	{
//		$delArr = $_POST['arr'];
//		$delArr[] = array();
		$delArr[] = $jsondata['arr'];
		//var_dump($delArr);
//		file_put_contents("test.log", "delArr: ".$delArr."\n", FILE_APPEND);
		dwopendb();
		foreach($delArr as $ide)
		{ 
//			echo $ide."\r\n";
			$exec="delete from staffbasesetting where skid=$ide AND staffname!=\"admin\";"; 
//			file_put_contents("test.log", "exec: ".$exec."\n", FILE_APPEND);
			$result=mysql_query($exec); 
			if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1)) 
			{ 
				echo '{"res":"success"}';
//				echo "<script language=\"JavaScript\">alert(\"没有找到记录，或者删除时出错\");</script><br/>"; 
//				echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/adminsetting.php',5000);</script><br/>";
//				exit; 
			} 
			else
			{ 
//				echo "<script language=\"JavaScript\">alert(\"序号 ".$ide." 已删除。\");</script><br/>"; 
/*				echo "<script language=\"JavaScript\">alert('授权成功。');</script><br/>";
				echo "<script language=\"JavaScript\">alert('序号 ".$ide." 已删除。');</script><br/>"; 
				echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/adminsetting.php',5000);</script><br/>";
*/
				echo '{"res":"fail"}';	
			}
			mysql_free_result($result);
		}		
		dwclosedb();
	}
	
	if($action == "dwadupdate")
	{
		dwupdate("update",false,"/door/adminsetting.php");
	}
	if($action == "dwadupdate_1")
	{
		dwupdate("update",false,"/door/adminsetting_1.php");
	}	
	if($action == "dwupdateauth_1")
	{
		dwupdate("update",true,"/door/adminsetting_1.php");
	}
	if($action == "dwupdateauth")
	{
		dwupdate("update",true,"/door/adminsetting.php");
	}
	if($action == "dwupdateadmin2")
	{
		dwupdate("update",false,"/door/staffbasesetting.php");
	}
	if($action == "dwupdateadmin8")
	{
		dwupdate("update",false,"/door/staffbasesetting.php");
	}	
	if($action == "dwupdateadmin12")
	{
		dwupdate("update",false,"/door/staffbasesetting.php");
	}
	if($action == "dwupdateadmin12_1")
	{
		dwupdate("update",false,"/door/staffbasesetting_1.php");
	}
	if($action == "dwview")
	{
		$skid = $_POST["skid"];
		//echo $skid."\r\n";
		// $skid = $skid["skid"];
		//echo $skid."\r\n";
		dwopendb();
//		$sqlstr="select staffnum,staffname,staffgender,staffage,picfilename,departmentID,jingruqishi1,jingrujieshu1,likaiqishi1,likaijieshu1,jingruqishi2,jingrujieshu2,likaiqishi2,likaijieshu2,jingruqishi3,jingrujieshu3,likaiqishi3,likaijieshu3,jingruqishi4,jingrujieshu4,likaiqishi4,likaijieshu4 from staffbasesetting where staffnum='$skid';"; 
		$sqlstr="select staffnum,staffname,staffgender,staffage,picfilename,departmentID from staffbasesetting where staffnum='$skid';";
		//mysql_query("SET NAMES utf8"); 
//		@file_put_contents("test.log", "\n sqlstr =".$sqlstr."\n", FILE_APPEND);
		$result=mysql_query($sqlstr); 
		$item = mysql_fetch_row($result);
		mysql_free_result($result);
		dwclosedb();
		// var_dump($item);
		//"{\"nrows\":\"".$rowsnum[0]."\",\"ncols\":\"5\",\"pageMaxium\":\"".$pagemax."\",
/*		$entrancevality1=$item[6]."-".$item[7];
		$leavevality1=$item[8]."-".$item[9];
		$entrancevality2=$item[10]."-".$item[11];
		$leavevality2=$item[12]."-".$item[13];
		$entrancevality3=$item[14]."-".$item[15];
		$leavevality3=$item[16]."-".$item[17];
		$entrancevality4=$item[18]."-".$item[19];
		$leavevality4=$item[20]."-".$item[21];
		echo "{\"staffnum\":\"".$item[0]."\",\"staffname\":\"".$item[1]."\",\"staffgender\":\"".$item[2]."\",\"staffage\":\"".$item[3]."\",\"picfilename\":\"".$item[4]."\",\"entrancevality1\":\"".$entrancevality1."\",\"leavevality1\":\"".$leavevality1."\",\"entrancevality2\":\"".$entrancevality2."\",\"leavevality2\":\"".$leavevality2."\",\"entrancevality3\":\"".$entrancevality3."\",\"leavevality3\":\"".$leavevality3."\",\"entrancevality4\":\"".$entrancevality4."\",\"leavevality4\":\"".$leavevality4.'"}';*/
		//var_dump($result);
		echo "{\"staffnum\":\"".$item[0]."\",\"staffname\":\"".$item[1]."\",\"staffgender\":\"".$item[2]."\",\"staffage\":\"".$item[3]."\",\"picfilename\":\"".$item[4]."\",\"departmentID\":\"".$item[5]."\"}";		
	}
	
	if($action == "dwaddadmin2")
	{
		dwupdate("add",true,"/door/staffbasesetting.php");
	}
	if($action == "dwaddadmin6")
	{
		dwupdate("add",true,"/door/staffbasesetting.php");
	}
	if($action == "dwaddadmin10")
	{
		dwupdate("add",true,"/door/staffbasesetting.php");
	}
	if($action == "dwaddadmin10_1")
	{
		dwupdate("add",true,"/door/staffbasesetting_1.php");
	}
	if($action == "dwgetadmin2")
	{
		$adminpagenum=$jsondata["admin2pagenum"]; 
//		if($adminpagenum=='admin2pagenum')
		if($adminpagenum)
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
		dwget($controlerpagenum,2,5,"s0");
	}
	if($action == "dwgetadmin5")
	{
		$adminpagenum=$jsondata["admin5pagenum"]; 
//		if($adminpagenum=='admin2pagenum')
		if($adminpagenum)
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
		dwget($controlerpagenum,1,5,"s50");
	}
	if($action == "dwgetadmin9")
	{
		$adminpagenum=$jsondata["admin9pagenum"]; 
//		if($adminpagenum=='admin2pagenum')
		if($adminpagenum)
		{
			$controlerpagenum = $adminpagenum;
		}
		else
		{
			$controlerpagenum = 1;
		}
		dwget($controlerpagenum,0,5,"s90");
	}
	if($action == "dwgetgatename")
	{
		$myconn=dwopendb();
		$strSql="select distinct gatename from gatesetting ORDER BY lasttime DESC;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$i=1;	
        while($dbResult = mysql_fetch_array($result))
	    {	        		   
		    if($i==1)
	        {			        
	    		$accesstab = "{\"s".$i.'_'."0\":\"".$dbResult[0].'"';						
		    }else
			{
			    $accesstab = $accesstab.",\"s".$i.'_'."0\":\"".$dbResult[0].'"';
			}
            $i++;
//                @file_put_contents("test.log", "\n i =".$i." accesstab =".$dbResult[$i-1]."\n", FILE_APPEND);				
	    }
		$accesstab = $accesstab.",\"nrows\":\"".($i-1)."\"}";
	    mysql_free_result($result);
		dwclosedb($myconn);
//			mysql_close($myconn);	
	    echo $accesstab;
	}
/*	if($action == "dwgetdepart")
	{
		$myconn=dwopendb();
		$strSql="select distinct region from gatesetting ORDER BY lasttime DESC;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$i=1;	
        while($dbResult = mysql_fetch_array($result))
	    {	        		   
		    if($i==1)
	        {			        
	    		$accesstab = "{\"s".$i.'_'."0\":\"".$dbResult[0].'"';						
		    }else
			{
			    $accesstab = $accesstab.",\"s".$i.'_'."0\":\"".$dbResult[0].'"';
			}
            $i++;
//                @file_put_contents("test.log", "\n i =".$i." accesstab =".$dbResult[$i-1]."\n", FILE_APPEND);				
	    }
		$accesstab = $accesstab.",\"nrows\":\"".($i-1)."\"}";
	    mysql_free_result($result);
		dwclosedb($myconn);
//			mysql_close($myconn);	
	    echo $accesstab;
	}*/
	if($action == "dwgetcontrolernum")
	{
		$myconn=dwopendb();
		$strSql="select distinct controlerNum,lasttime from gatesetting ORDER BY lasttime DESC;";
//		$strSql="select distinct controlerNum,lasttime from gatesetting ORDER BY lasttime ASC;";
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$accesstab = "{";	
		$i=1;
        while($dbResult = mysql_fetch_array($result))
	    {	        		   
//		    if($i==1)
//	        {			        
//	    		$accesstab = "{\"s".$i.'_'."0\":\"".$dbResult[0].'"';						
//		    }else
//			{
			    $accesstab = $accesstab."\"s".$i.'_'."0\":\"".$dbResult[0].'",';
//			}
            $i++;
//            @file_put_contents("test.log", "\n i =".$i-1." accesstab =".$dbResult[0]."\n", FILE_APPEND);				
	    }
		$accesstab = $accesstab."\"nrows\":\"".($i-1)."\"}";
	    mysql_free_result($result);
		dwclosedb($myconn);
//			mysql_close($myconn);	
	    echo $accesstab;
	}
	if($action == "dwgetstaffnum")
	{
		dwopendb();
		$strSql="select MAX(rowid) from staffbasesetting;";
//		$result=mysql_query($strSql,$myconn);
		$result=mysql_query($strSql);		
        while($dbResult = mysql_fetch_array($result))
	    {	        		   		        
	    	$accesstab = "{\"maxskid\":\"".$dbResult[0]."\"}";	
//            @file_put_contents("test.log", "\n accesstab =".$accesstab." line: ".__LINE__."\n", FILE_APPEND);				
	    }
	    mysql_free_result($result);
		dwclosedb();
//			mysql_close($myconn);	
	    echo $accesstab;
	}
	if($action == "dwdel")
	{
		//echo "del:\r\n";
		$delArr = $_POST['arr'];
		//var_dump($delArr);
		$myconn=dwopendb();
		foreach($delArr as $ide)
		{ 
//			echo $ide."\r\n";
//			$exec="delete from staffbasesetting where skid=$ide";
/*			$exec="SELECT distinct ControlerNum from staffbasesetting where staffnum=$ide and staffnum!='1';";
			$result=mysql_query($exec);
			$dbResult = mysql_fetch_array($result);
			if($dbResult[0]==="ALL")
			{
		
				$strSql="SELECT DISTINCT controlernum FROM gatesetting ORDER BY lasttime DESC;";
				$result=mysql_query($strSql,$myconn);
	//			$result=mysql_query($strSql);
				while($dbResult = mysql_fetch_row($result))
				{
					$transid=uuid();
					$cmdstr="{\"dwdevice\":\"". $dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_DELETE_USERINFO\",\"userid\":\"".$ide." \"}";
					dwsendtoserver($cmdstr,$myconn);
				}
				mysql_free_result($result);
			}else
			{
				$transid=uuid();
				$cmdstr="{\"dwdevice\":\"". $dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_DELETE_USERINFO\",\"userid\":\"".$ide." \"}";
				dwsendtoserver($cmdstr,$myconn);
			}*/
 
			$exec="delete from staffbasesetting where staffnum='$ide' and staffnum!='1';";
			$result=mysql_query($exec,$myconn);
			file_put_contents("test.log", "exec: ".$exec." LINE: ".__LINE__ ."\n", FILE_APPEND);
			$rc = mysql_affected_rows($myconn) or die("mysql_affected_rows err: ".mysql_errno());
			file_put_contents("test.log", "mysql_affected_rows: ".$rc." LINE: ".__LINE__ ."\n", FILE_APPEND);
			if(($rc==0) || ($rc==-1)) 
			{ 
				echo "fail";
				file_put_contents("test.log", "\n del fail" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
//				echo "没有找到记录，或者删除时出错."; 
//				exit; 
			}else
			{ 
				file_put_contents("test.log", "\n del ok ide: ".$ide." LINE: ".__LINE__ ."\n", FILE_APPEND);
				$isrc=is_dir("./zaopian/$ide") or die("is_dir err: ");
				file_put_contents("test.log", "del: zaopian/$ide" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
				if($isrc)
				{
//					file_put_contents("test.log", "del: zaopian/$ide" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
					delDirAndFile("./zaopian/$ide");
//					rmdir("./zaopian/$ide") or die("rmdir err ");
					file_put_contents("test.log", "del: zaopian/$ide" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
				}else
				{
					file_put_contents("test.log", "del: zaopian/$ide" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
				}
				
				if(unlink("./biduilujing/$ide.dat"))
				{
					echo "success";
//					echo "信息已经删除.";
					file_put_contents("test.log", "del success: biduilujing/$ide.dat" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
				}else
				{
					echo "fail";
//					echo "没有找到记录，或者删除时出错.";
					file_put_contents("test.log", "\n del fail: biduilujing/$ide.dat" ." LINE: ".__LINE__ ."\n", FILE_APPEND);
				}
				
				//echo "学生信息已经删除"; 
			}
		}
		dwclosedb($myconn);
	}
	
	if($action == "dwgatedownload")
	{
		$strSql='';
		$dbResult=array();
		$controlernum = $_POST["controlernum"];	
		$WebADDR = $_POST["WebADDR"];
		$WebPORT = $_POST["WebPORT"];
		$TcpPORT = $_POST["TcpPORT"];
	//	$cmdresultpath = $_POST["cmdresult"];
		$realtimepath = $_POST["realtime"];
	//	$DetectDevicepath = $_POST["DetectDevice"];
		$CameraADDR = $_POST["CameraADDR"];
		$CameraPORT = $_POST["CameraPORT"];
		$CameraRTSP = $_POST["CameraRTSP"];

		$jianquanfangshi = $_POST["jqfs"];
		$sVersion = $_POST["sVersion"];
//		file_put_contents("test.log", "Camera1ADDR ".$Camera1ADDR." _POST ".$_POST["Camera0rtsp"]." Camera111rtsp ".$Camera0rtsp." Camera1rtsp ".$Camera1rtsp." Camera2rtsp ".$Camera2rtsp." Camera3rtsp ".$Camera3rtsp." line: ".__LINE__."\n", FILE_APPEND);

//		if(!$WebADDR||!$WebPORT||!$TcpPORT||!$realtimepath||!$Camera0ADDR||!$Camera0PORT||!$Camera1ADDR||!$Camera1PORT||!$sVersion||!$jianquanfangshi)
		if(!$WebADDR||!$WebPORT||!$TcpPORT||!$realtimepath||!$CameraADDR||!$CameraPORT||!$sVersion||!$jianquanfangshi)
		{	    
			echo "<script language=\"JavaScript\">alert('.....输入为空或太长。');</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
//			file_put_contents("test.log", "\n null \n", FILE_APPEND);
			return;	
		}
		$gatename = $_POST["gatename"];
		$gatenum = $_POST["gatenum"];
		$region=$_POST["region"];
		$controlmethod=$_POST["controlmethod"];
		$delayopentime = $_POST["delayopentime"];
		$delayclosetime = $_POST["delayclosetime"];
		$sensorstat=$_POST["sensorstat"];
		$attendancecheck=$_POST["attendancecheck"];
		$antipassback = $_POST["antipassback"];
		file_put_contents("test.log", "1:...".$controlerIP.$controlerPORT.$WebADDR.$WebPORT.$CameraADDR.$controlernum.$gatenum.$gatename.$region.$controlmethod.$delayopentime.$delayclosetime.$sensorstat.$attendancecheck.$antipassback." line ".__LINE__."\n", FILE_APPEND);		
		if($gatenum===NULL || !$gatename || !$region || !$controlmethod || !$antipassback || !$sensorstat || !$attendancecheck || $delayopentime===NULL || $delayclosetime===NULL || !$controlernum)
		{	    
			echo "<script language=\"JavaScript\">alert('输入为空或太长.....。');</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
	//		file_put_contents("test.log", "\n null \n", FILE_APPEND);
			return;	
		}   
		$myconn=dwopendb();
		if($controlernum ==="ALL")
		{
//			$strSql="SELECT DISTINCT controlernum FROM gatesetting WHERE controlerNum !='ALL' ORDER BY lasttime DESC;";
			$strSql="SELECT DISTINCT controlerNum,lasttime FROM gatesetting WHERE controlerNum !='ALL' ORDER BY lasttime DESC;";
			$result=mysql_query($strSql,$myconn);
//			$result=mysql_query($strSql);
			while($dbResult = mysql_fetch_row($result))
			{
				if($gatenum==="all")
				{
//					dwclosedb($myconn);
					for($i=0;$i<4;$i++)
					{	
						$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP='$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum = '$dbResult[0]' AND gatenum= '$i';";
						$result11=mysql_query($strSql,$myconn);
//						@file_put_contents("test.log", "\n strSql00 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
						if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1))
						{ 
							mysql_free_result($result11);
//							mysql_close($myconn);
//							$string = "Can't exec database : ".mysql_error();
//							file_put_contents("test.log", $string, FILE_APPEND);
							dwclosedb($myconn);
							echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
							echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
							return;							
						} 
//						$item = mysql_fetch_row($result1);
						mysql_free_result($result11);
//						dwclosedb($myconn);
						$transid=uuid();
				
						$cmdstr="{\"dwdevice\":\"". $dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
				/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
						$result44=mysql_query($strSql,$myconn);
				//		$result=mysql_query($strSql);
						$dbResult44 = mysql_fetch_array($result44);
						if($dbResult44[0])
						{
							$TCPport = $dbResult44[0];
						}else
						{
							$TCPport = "1119";
						}
						mysql_free_result($result44);*/
						dwsendtoserver($cmdstr,$myconn);
//						file_put_contents("test.log", "\n cmdstr_0: ".$cmdstr." TCPport: ".$TCPport."\n", FILE_APPEND);
					}
				}else
				{
					$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP='$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum = '$dbResult[0]' AND gatenum= '$gatenum';";
					$result11=mysql_query($strSql,$myconn);
//					@file_put_contents("test.log", "\n strSql01 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
					if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1))	
					{ 
						mysql_free_result($result11);
						dwclosedb($myconn);
						echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
						return;	
					} 
//					$item = mysql_fetch_row($result1);
					mysql_free_result($result11);
//					dwclosedb($myconn);
					$transid=uuid();
						
					$cmdstr="{\"dwdevice\":\"".$dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
			/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
					$result44=mysql_query($strSql,$myconn);
			//		$result=mysql_query($strSql);
					$dbResult44 = mysql_fetch_array($result44);
					if($dbResult44[0])
					{
						$TCPport = $dbResult44[0];
					}else
					{
						$TCPport = "1119";
					}
					mysql_free_result($result44);*/
					dwsendtoserver($cmdstr,$myconn);
//					file_put_contents("test.log", "\n cmdstr_1: ".$cmdstr." TCPport: ".$TCPport."\n", FILE_APPEND);
				}
			}	
		}else if($controlernum)
		{
			$strSql="SELECT MAX(skid) FROM gatesetting WHERE controlerNum ='$controlernum';";
			$result=mysql_query($strSql,$myconn);
			$dbResult = mysql_fetch_array($result);
			mysql_free_result($result);
		//	file_put_contents("test.log", "\n strSql".$strSql, FILE_APPEND);
			if($dbResult[0])
			{
				if($gatenum==="all")
				{
//					dwclosedb($myconn);
					for($i=0;$i<4;$i++)
					{
//						$myconn=dwopendb();						
						$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP= '$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',,jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum ='$controlernum' AND gatenum= '$i';";
						$result=mysql_query($strSql,$myconn);
//						@file_put_contents("test.log", "\n strSql02 =".$strSql."\n", FILE_APPEND);

						$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
						mysql_free_result($result);
				/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
						$result44=mysql_query($strSql,$myconn);
				//		$result=mysql_query($strSql);
						$dbResult44 = mysql_fetch_array($result44);
						if($dbResult44[0])
						{
							$TCPport = $dbResult44[0];
						}else
						{
							$TCPport = "1119";
						}
						mysql_free_result($result44);*/
						dwsendtoserver($cmdstr,$myconn);
//						file_put_contents("test.log", "\n cmdstr_2: ".$cmdstr." TCPport: ".$TCPport." 	LINE ".__LINE__."\n", FILE_APPEND);
					}
				}else
				{
					$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP= '$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum = '$controlernum' AND gatenum= '$gatenum';";
					$result=mysql_query($strSql,$myconn);
					@file_put_contents("test.log", "\n strSql03 =".$strSql." line ".__LINE__."\n", FILE_APPEND);

					$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
					mysql_free_result($result);
			/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
					$result44=mysql_query($strSql,$myconn);
			//		$result=mysql_query($strSql);
					$dbResult44 = mysql_fetch_array($result44);
					if($dbResult44[0])
					{
						$TCPport = $dbResult44[0];
					}else
					{
						$TCPport = "1119";
					}
					mysql_free_result($result44);*/
					dwsendtoserver($cmdstr,$myconn);
//					file_put_contents("test.log", "\n cmdstr_3: ".$cmdstr." TCPport: ".$TCPport."\n", FILE_APPEND);
				}
			}else
			{
				if($gatenum==="all")
				{
//					dwclosedb($myconn);
					for($i=0;$i<4;$i++)
					{
						$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,region,antipassback,serverIP,serverPORT,tcpPORT,jianquanfangshi,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,IP,PORT,lianjie,lasttime) VALUES('".$controlernum."','$i','$gatename','$controlmethod','$delayopentime','$delayclosetime','$sensorstat','$attendancecheck','$region','$antipassback','$WebADDR','$WebPORT','$TcpPORT','$jianquanfangshi','$realtimepath','$CameraADDR','$CameraPORT','$CameraRTSP','$sVersion','127.0.0.1','80','offline','2016-01-01 00:00:00');";
						$result=mysql_query($strSql,$myconn);
//						@file_put_contents("test.log", "\n strSql04 =".$strSql."\n", FILE_APPEND);
	
						$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
						mysql_free_result($result);
				/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
						$result44=mysql_query($strSql,$myconn);
				//		$result=mysql_query($strSql);
						$dbResult44 = mysql_fetch_array($result44);
						if($dbResult44[0])
						{
							$TCPport = $dbResult44[0];
						}else
						{
							$TCPport = "1119";
						}
						mysql_free_result($result44);*/
						dwsendtoserver($cmdstr,$myconn);
//						file_put_contents("test.log", "\n cmdstr_4: ".$cmdstr."\n", FILE_APPEND);
					}
				}else
				{
					$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,region,antipassback,serverIP,serverPORT,tcpPORT,jianquanfangshi,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,IP,PORT,lianjie,lasttime) VALUES('".$controlernum."','$gatenum','$gatename','$controlmethod','$delayopentime','$delayclosetime','$sensorstat','$attendancecheck','$region','$antipassback','$WebADDR','$WebPORT','$TcpPORT','$jianquanfangshi','$realtimepath','$CameraADDR','$CameraPORT','$CameraRTSP','$sVersion','127.0.0.1','80','offline','2016-01-01 00:00:00');";
					$result=mysql_query($strSql,$myconn);
//					@file_put_contents("test.log", "\n strSql05 =".$strSql."\n", FILE_APPEND);

					$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
					mysql_free_result($result);
			/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
					$result44=mysql_query($strSql,$myconn);
			//		$result=mysql_query($strSql);
					$dbResult44 = mysql_fetch_array($result44);
					if($dbResult44[0])
					{
						$TCPport = $dbResult44[0];
					}else
					{
						$TCPport = "1119";
					}
					mysql_free_result($result44);*/
					dwsendtoserver($cmdstr,$myconn);
//					file_put_contents("test.log", "\n cmdstr_5: ".$cmdstr."\n", FILE_APPEND);
				}	
			}
//			$result=mysql_query($strSql,$myconn);
//			mysql_free_result($result);
//			dwsendtoserver($cmdstr);
//			file_put_contents("test.log", "\n cmdstr_1: ".$cmdstr."\n", FILE_APPEND);
		}
		dwclosedb($myconn);
//			mysql_close($myconn);
		echo "<script language=\"JavaScript\">alert('下发成功。');</script><br/>";
		echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
		return;
	}

	if($action == "dwgetgatetab")
	{
		$i=1;  
		$strSql='';
		$gatetab='{';
		$dbResult=array();
		$controlerNum=$jsondata["ControlerNum"];
		$gatenum=$jsondata["gatenum"];
		$myconn=dwopendb();
		if($gatenum==="all")
		{
			$strSql="select gatename,region,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback,serverIP,serverPORT,tcpPORT,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,jianquanfangshi from gatesetting WHERE controlerNum= '$controlerNum' AND gatenum='0';";
		}else
		{
			$strSql="select gatename,region,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback,serverIP,serverPORT,tcpPORT,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,jianquanfangshi from gatesetting WHERE controlerNum= '$controlerNum' AND gatenum='$gatenum';";
		}
		$result=mysql_query($strSql,$myconn);	        
	//    @file_put_contents("test.log", "\n strSql =".$strSql." \ndata:".$data." controlerNum:".$controlerNum."\n", FILE_APPEND);
		while($dbResult = mysql_fetch_array($result))
		{	        		   
			for($j=0;$j<(17);$j++)
			{			   
				$gatetab = $gatetab."\"s".$i.'_'.$j."\":\"".$dbResult[$j].'",';
			}
			$i++;	
	//			@file_put_contents("test.log", "\n i =".$i." gatetab =".$dbResult[$i-1]."\n", FILE_APPEND);				
		}
		if($i===1)
		{
			for($j=0;$j<(17);$j++)
			{
				$gatetab = $gatetab."\"s1_".$j."\":\"\",";
			}
		}	
		$gatetab = $gatetab."\"nrows\":\"".($i-1)."\",\"ncols\":\"17\"}";
		
		mysql_free_result($result);
		dwclosedb($myconn);	
		echo $gatetab;
	}
	
	if($action == "dwclientopen")
	{
		$dwshebeihao=$jsondata["dwshebeihao"];
		$dwcmd=$jsondata["dwcmd"];
		$gatenum=$jsondata["menghao"];
//		if($deresultArr["dwclient"])
		$cmdstr="";
		if($dwshebeihao && $dwcmd)
		{
			$cmdstr="{\"dwdevice\":\"".$dwshebeihao."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"".$dwcmd."\",\"gatenum\":\"".$gatenum."\"}";
//			file_put_contents("test.log", "cmdstr =".$cmdstr." LINE".__LINE__."\n", FILE_APPEND);
		}
//		file_put_contents("test.log", "cmdstr =".$cmdstr." LINE ".__LINE__."\n", FILE_APPEND);
	/*	$strSql="SELECT TcpPORT FROM serversetting;";
		$result=mysql_query($strSql,$myconn);
		$dbResult = mysql_fetch_array($result);
		dwclosedb($myconn);	
		if($dbResult[0])
		{
			$TCPport = $dbResult[0];
		}else
		{
			$TCPport = "1119";
		}*/
		if(dwsendtoserver($cmdstr,$myconn))
		{
			echo "{\"result\":\"OK\"}";
		}else
		{
			echo "{\"result\":\"ERROR\"}";
		}
//		file_put_contents("test.log", "cmdstr =".$cmdstr." TCPport ".$TCPport." LINE ".__LINE__."\n", FILE_APPEND);
	}

	if($action == "dwrlqietu")
	{	
		$shebeihao=$jsondata["shebeihao"];
		$menghao=$jsondata["menghao"];
		$gonghao=$jsondata["gonghao"];
		file_put_contents("test.log", "shebeihao: ".$shebeihao." menghao: ".$menghao." gonghao: ".$gonghao." LINE ".__LINE__."\n", FILE_APPEND);
		if($menghao== 'all' || $menghao== '全部') $menghao ='0';

		$myconn = dwopendb();
		if($shebeihao=== 'ALL')
		{
			$strSql = "SELECT DISTINCT controlerNum FROM gatesetting WHERE $shebeihao!= 'ALL' AND lasttime =(SELECT MAX(lasttime) FROM gatesetting);";
			$result=mysql_query($strSql,$myconn);	        		    
			while($dbResult = mysql_fetch_array($result))
			{
				$shebeihao = $dbResult[0];
			}
			mysql_free_result($result);
			@file_put_contents("test.log", "strSql =".$strSql." \ndata:".$data." controlerNum:".$$shebeihao." LINE ".__LINE__."\n", FILE_APPEND);
		}
		$dbResult=array();
/*		if($shebeihao)
		{
			$strSql = "SELECT CameraRTSP FROM gatesetting WHERE controlerNum ='$shebeihao' AND gatenum ='$menghao';";
			$result=mysql_query($strSql,$myconn);	        
		    @file_put_contents("test.log", "strSql =".$strSql." \ndata: ".$data." controlerNum:".$shebeihao." LINE ".__LINE__."\n", FILE_APPEND);
			while($dbResult = mysql_fetch_array($result))
			{
				$CameraRTSP=$dbResult[0];
			}
			mysql_free_result($result);
		}*/
		dwclosedb($myconn);
//		if($CameraRTSP)
		if($shebeihao)
		{
			$qietulujing = $_SERVER['DOCUMENT_ROOT']."/qietu/".$gonghao."/";
			if(!is_dir($qietulujing))
			{
				$mode = 0766;	
				mkdir($qietulujing, $mode);
			}
		}
		file_put_contents("test.log", "{\"dongzuo\":\"qietu\",\"qietulujing\":\"".$qietulujing."\",\"shebeihao\":\"".$shebeihao."\",\"menghao\":\"".$menghao."\"}"." LINE ".__LINE__."\n", FILE_APPEND);	
/*			$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"qietu\",\"qietulujing\":\"".$qietulujing."\",\"CameraRTSP\":\"".$CameraRTSP."\"}");
			@file_put_contents("test.log", "{\"dongzuo\":\"qietu\",\"qietulujing\":\"".$qietulujing."\",\"CameraRTSP\":\"".$CameraRTSP."\"}"." LINE ".__LINE__."\n", FILE_APPEND);
			if($fanhuizhi===FALSE)
			{
				echo "{\"jieguo\":\"shibai\"}";
			}else
			{
				echo "{\"jieguo\":\"chenggong\"}";
			}
		}else
		{
			echo "{\"jieguo\":\"shibai\"}";
		}*/
		$minglingchuan=$_SERVER['DOCUMENT_ROOT']."/cgi-bin/dwqietu.sh ".$qietulujing." ".$shebeihao." ".$menghao." 2>&1";
		exec($minglingchuan, $output, $fanhuizhi);
		$fanhuichuan=implode(" ",$output);
		file_put_contents("test.log",'dwqietu.sh 2>&1:'.$fanhuichuan.' fanhuizhi:'.$fanhuizhi.' minglingchuan '.$minglingchuan." LINE ".__LINE__."\n", FILE_APPEND); 
		$pos = strpos($fanhuichuan,"dwrlqietu: ok");
		if( $fanhuizhi || $pos === false)
		{			
			echo '{"errorMsg":"'.$fanhuichuan.'"}';
		}else
		{
			echo '{"success":"true"}';
		}
		return;
//		file_put_contents("test.log", 'exec("/home/rs/dwf/www/cgi-bin/dwtingzhi.sh") fanhuizhi:'.$fanhuizhi." LINE ".__LINE__."\n", FILE_APPEND);
	}

	if($action == "dwrltingzhi")
	{	
		$mingling=$_SERVER['DOCUMENT_ROOT']."/cgi-bin/dwtingzhi.sh 2>&1";
		exec($mingling, $output, $fanhuizhi);
		file_put_contents("test.log", "mingling: ".$mingling.' output:'.implode(" ",$output).' fanhuizhi:'.$fanhuizhi." LINE ".__LINE__."\n", FILE_APPEND); 
		if($fanhuizhi)
		{
			echo '{"errorMsg":$output}';
		}else
		{
			echo '{"success":"true"}';
		}
		return;
//		file_put_contents("test.log", 'exec("$_SERVER['DOCUMENT_ROOT']/www/cgi-bin/dwtingzhi.sh") fanhuizhi:'.$fanhuizhi." LINE ".__LINE__."\n", FILE_APPEND);
	}

	if($action == "dwrlqidong")
	{
		$mingling=$_SERVER['DOCUMENT_ROOT']."/cgi-bin/dwqidong.sh 2>&1";
		exec($mingling, $output, $fanhuizhi);
		$fanhuichuan=implode(" ",$output);
		file_put_contents("test.log","mingling: ".$mingling.' | output:'.$fanhuichuan.' | fanhuizhi:'.$fanhuizhi." LINE ".__LINE__."\n", FILE_APPEND); 
		$pos = strpos($fanhuichuan,"dwqidong err");
		//if( !$fanhuizhi && $pos === false)
		if($pos === false)
		{			
			echo '{"success":"true"}';
		}else
		{
			echo '{"errorMsg":"'.$fanhuichuan.'"}';
		}
		exit(0);
/*		if($fanhuizhi)
		{
			echo '{"errorMsg":$output}';
		}else
		{
			echo '{"success":"true"}';
		}*/
//		file_put_contents("test.log", 'exec("/home/rs/dwf/www/cgi-bin/dwqidong.sh") fanhuizhi:'.$fanhuizhi." LINE ".__LINE__."\n", FILE_APPEND); 
	}

	if($action == "dwdongtaiqidong")
	{
		$ControlerNum=$jsondata["ControlerNum"];
		$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"qidong\",\"shebeihao\":\"$ControlerNum\"}");
		if($fanhuizhi===FALSE)
		{
			echo "{\"jieguo\":\"shibai\"}";
		}else
		{
			echo "{\"jieguo\":\"chenggong\"}";
		}
		file_put_contents("test.log", "{\"dongzuo\":\"qidong\",\"shebeihao\":\"$ControlerNum\"}"." LINE ".__LINE__."\n", FILE_APPEND); 
	}

	if($action == "dwdongtaitingzhi")
	{
		$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"tingzhi\"}");
		if($fanhuizhi===FALSE)
		{
			echo "{\"jieguo\":\"shibai\"}";
		}else
		{
			echo "{\"jieguo\":\"chenggong\"}";
		}
	}

	if($action == "dwqietu")
	{
		$shebeihao=$jsondata["shebeihao"];
		$menghao=$jsondata["menghao"];
		$gonghao=$jsondata["gonghao"];
		file_put_contents("test.log", "shebeihao: ".$shebeihao." menghao: ".$menghao." gonghao: ".$gonghao." LINE ".__LINE__."\n", FILE_APPEND);
		if($menghao== 'all') $menghao ='0';

		$myconn = dwopendb();
		if($shebeihao=== 'ALL')
		{
			$strSql = "SELECT DISTINCT controlerNum FROM gatesetting WHERE $shebeihao!= 'ALL' AND lasttime =(SELECT MAX(lasttime) FROM gatesetting);";
			$result=mysql_query($strSql,$myconn);	        		    
			while($dbResult = mysql_fetch_array($result))
			{
				$shebeihao = $dbResult[0];
			}
			mysql_free_result($result);
			@file_put_contents("test.log", "strSql =".$strSql." \ndata:".$data." controlerNum:".$$shebeihao." LINE ".__LINE__."\n", FILE_APPEND);
		}
		$dbResult=array();
		if($shebeihao)
		{
			$strSql = "SELECT CameraRTSP FROM gatesetting WHERE controlerNum ='$shebeihao' AND gatenum ='$menghao';";
			$result=mysql_query($strSql,$myconn);	        
		    @file_put_contents("test.log", "strSql =".$strSql." \ndata: ".$data." controlerNum:".$shebeihao." LINE ".__LINE__."\n", FILE_APPEND);
			while($dbResult = mysql_fetch_array($result))
			{
				$CameraRTSP=$dbResult[0];
			}
			mysql_free_result($result);
		}
		dwclosedb($myconn);
		if($CameraRTSP)
		{
			$qietulujing = $_SERVER['DOCUMENT_ROOT']."/qietu/".$gonghao."/";
			if(!is_dir($qietulujing))
			{
				$mode = 0766;	
				mkdir($qietulujing, $mode);
			}
			$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"qietu\",\"qietulujing\":\"".$qietulujing."\",\"CameraRTSP\":\"".$CameraRTSP."\"}");
			@file_put_contents("test.log", "{\"dongzuo\":\"qietu\",\"qietulujing\":\"".$qietulujing."\",\"CameraRTSP\":\"".$CameraRTSP."\"}"." LINE ".__LINE__."\n", FILE_APPEND);
			if($fanhuizhi===FALSE)
			{
				echo "{\"jieguo\":\"shibai\"}";
			}else
			{
				echo "{\"jieguo\":\"chenggong\"}";
			}
		}else
		{
			echo "{\"jieguo\":\"shibai\"}";
		}		
	}

	if($action == "dwjingkouqietu")
	{
		$gonghao=$jsondata["gonghao"];
		$qietulujing = $_SERVER['DOCUMENT_ROOT']."/zaopian/".$gonghao."/";
		$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"jingkouqietu\",\"qietulujing\":\"".$qietulujing."\"}");
		if($fanhuizhi===FALSE)
		{
			echo "{\"jieguo\":\"shibai\"}";
		}else
		{
			echo "{\"jieguo\":\"chenggong\"}";
		}
	}

	if($action == "dwchukouqietu")
	{
		$gonghao=$jsondata["gonghao"];
		$qietulujing = $_SERVER['DOCUMENT_ROOT']."/zaopian/".$gonghao."/";
		$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"chukouqietu\",\"qietulujing\":\"".$qietulujing."\"}");
		if($fanhuizhi===FALSE)
		{
			echo "{\"jieguo\":\"shibai\"}";
		}else
		{
			echo "{\"jieguo\":\"chenggong\"}";
		}
	}

	if($action == "dwxunlian")
	{
		$xunlianlujing = $_SERVER['DOCUMENT_ROOT']."/zaopian";
		$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"xunlian\",\"xunlianlujing\":\"".$xunlianlujing."\"}");
		if($fanhuizhi===FALSE)
		{
			echo "{\"jieguo\":\"shibai\"}";
		}else
		{
			echo "{\"jieguo\":\"chenggong\"}";
		}
	}
	
	function dwget($controlerpagenum,$auth,$showrow,$s)
	{
		$pagestart=1;
		$pageend=1;
		$i=1;
		$j=1;  
		$strSql='';
		$blank=false;
		$accesstab='{';
		$dbResult=array();
		$rowsnum=array();
		$myconn=dwopendb();			
		$strSql="select COUNT(*) from staffbasesetting;";
//		@file_put_contents("test.log", "\n strSql: ".$strSql."\n", FILE_APPEND);
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);		
		$rowsnum = mysql_fetch_array($result);
		mysql_free_result($result);
//		@file_put_contents("test.log", "\n rowsnum: ".$rowsnum[0]."\n", FILE_APPEND);
		if($rowsnum[0]==0)
		{
			$blank = true;
//			@file_put_contents("test.log", "\n ...rowsnum: ".$rowsnum1[0]."\n", FILE_APPEND);
		}		
		$pagemax=1;
		$srow = $showrow*1.0;
		$pagemax = (($rowsnum[0]/$srow)-(int)($rowsnum[0]/$srow))>0.?(int)($rowsnum[0]/$srow)+1:(int)($rowsnum[0]/$srow);
		if($pagemax<1) $pagemax=1;
		if($controlerpagenum>$pagemax) $controlerpagenum=$pagemax;
		$pagestart=$showrow*$controlerpagenum-$showrow;
		$pageend=$showrow;
//		@file_put_contents("test.log", "\n rowsnum: ".$rowsnum[0]." srow: ".$srow." showrow: ".$showrow." pagemax: ".$pagemax."\n", FILE_APPEND);
		 //如果请求的当前页是最后一页，则返回的条目数取余数，否则固定为10；
		if($controlerpagenum == $pagemax)
		{
			$rowsnum[0] = $rowsnum[0]%$showrow;
			if($rowsnum[0] == 0)
			{
				$rowsnum[0] = $showrow;
			}
		}
		else
		{
			$rowsnum[0] = $showrow;
		}
//		@file_put_contents("test.log", "\n ..rowsnum: ".$rowsnum[0]." showrow: ".$showrow." pagemax: ".$pagemax."\n", FILE_APPEND);
//		$strSql="select skid,staffnum,staffname,cardnum,departmentname,controlerNum,gatenum,periodofvalitystart,periodofvalityend from staffbasesetting WHERE synstate=".$auth." limit ".$pagestart.','.$pageend.';';
		$strSql="select staffnum,staffname,cardnum,departmentname,controlerNum,gatenum,periodofvalitystart,periodofvalityend from staffbasesetting ORDER BY rowid DESC limit ".$pagestart.','.$pageend.';';
//        file_put_contents("test.log", "strSql: ".$strSql."\n", FILE_APPEND);
		$result=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);	
		while($dbResult = mysql_fetch_array($result))
		{	        			
			for($j=1;$j<=8;$j++)
			{			   
/*				if($i==1 && $j==1)
				{			        
					$accesstab = "{\"nrows\":\"".$rowsnum[0]."\",\"ncols\":\"9\",\"pageMaxium\":\"".$pagemax."\",\"controlerpagenum\":\"".$controlerpagenum."\",\"".$s.$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'"';						
				}else
				{*/
					$accesstab = $accesstab."\"".$s.$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'",';
//				}
			}
			$i++;			
		}
//    }	
/*		if(!$blank)
		{
			$accesstab = $accesstab."}";
//			@file_put_contents("test.log", "\n accesstab: ".$accesstab."\n", FILE_APPEND);
		}
		else
		{*/
		$i-=1;
		$accesstab =$accesstab."\"nrows\":\"$i\",\"ncols\":\"9\",\"pageMaxium\":\"$pagemax\",\"controlerpagenum\":\"$controlerpagenum\"}";
//		@file_put_contents("test.log", "\n accesstab: ".$accesstab."\n", FILE_APPEND);
//		}	
		mysql_free_result($result);
		dwclosedb($myconn);
		echo $accesstab;
	}
	
	function dwsavepicfile($destination_folder,$picfilename,$url,$gonghao)
	{
		$max_file_size = 500*1024;
		$uptypes=array(  
		'image/jpg',  
		'image/jpeg',  
		'image/png',  
		'image/pjpeg',  
		'image/gif',  
		'image/bmp',  
		'image/x-png'  
		); 
		$pinfo=pathinfo($picfilename);
		$picfilename = $destination_folder.$pinfo["basename"]; 
		if(!file_exists($destination_folder))  
		{  
			mkdir($destination_folder,0777);
			chmod($destination_folder, 0777);
		}

		if (!is_uploaded_file($_FILES["filename"]["tmp_name"]))  
		//是否存在文件  
		{  
			echo "<script language=\"JavaScript\">alert('图片文件不存在。');</script><br/>";
			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
			return -1;	
		}else 
		{
			$file = $_FILES["filename"];  
			if($max_file_size < $file["size"])  
			//检查文件大小  
			{  
				echo "<script language=\"JavaScript\">alert('图片文件太大。');</script><br/>";
				echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
				return -1;	
			}else
			{		  
				if(!in_array($file["type"], $uptypes))  
				//检查文件类型  
				{  
					echo "<script language=\"JavaScript\">alert('\"图片文件类型不符。\"".$file["type"]."。');</script><br/>";
					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
					return -1;	
				}else
				{				  
					$filename=$file["tmp_name"];  
//					$image_size = getimagesize($filename);  
					$pinfo=pathinfo($file["name"]);  
					$real_filename = $pinfo["basename"];
					$ftype=$pinfo['extension'];  
//					$destination = $destination_folder.$real_filename;
					$destination = $_SERVER['DOCUMENT_ROOT']."/".$destination_folder.$gonghao.'.'.$ftype;
//					file_put_contents("test.log", "\n gonghao: ".$gonghao." destination_folder: ".$destination_folder." ftype: ".$ftype." destination: ".$destination." LINE: ".__LINE__."\n", FILE_APPEND); 
					if (file_exists($destination) )  
					{  
						echo "<script language=\"JavaScript\">alert('同名图片文件已经存在了。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//						return -1;	
					}  
				  	
					if(!move_uploaded_file ($filename, $destination))  
					{  
						echo "<script language=\"JavaScript\">alert('移动图片文件出错。');</script><br/>";
						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
						return -1;	
					}else
					{
						$biduilujing=$_SERVER['DOCUMENT_ROOT']."/biduilujing/";
//						file_put_contents("test.log", "{\"dongzuo\":\"dwquzhi\",\"zaopianquanming\":\"$destination\",\"gonghao\":\"$gonghao\",\"biduilujing\":\"$biduilujing\"}"." LINE: ".__LINE__."\n", FILE_APPEND);
						$fanhuizhi=file_put_contents("cgi-bin/qidongtingzhi.txt", "{\"dongzuo\":\"dwquzhi\",\"zaopianquanming\":\"$destination\",\"gonghao\":\"$gonghao\",\"biduilujing\":\"$biduilujing\"}");
						if($fanhuizhi===FALSE)
						{
							echo "<script language=\"JavaScript\">alert('增加图片文件出错。');</script><br/>";
							echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
						}else
						{
							echo "<script language=\"JavaScript\">alert('增加图片文件成功。');</script><br/>";
							echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
						}
						return 0;
					}
//					file_put_contents("test.log", "\n filename: ".$filename." image_size: ".$image_size." ftype: ".$ftype." destination: ".$destination." LINE: ".__LINE__."\n", FILE_APPEND);
				}
			}
		}		
	}

	function dwupdate($add,$auth,$url)
	{
		$strSql="";
		$staffnum = $_POST["staffnum"];
		$staffname = $_POST["staffname"];
		$cardnum = $_POST["cardnum"];
		$departmentname = $_POST["departmentname"];
		$controlerNum = $_POST["controlernum"];
		$departmentID = $_POST["departmentID"];
		$gatenum = $_POST["gatenum"];
		$gatename = $_POST["gatename"];
//		$staffauth = $_POST["staffauth"];
		$staffsign = "1";
//		$dwpassword = $_POST["dwpassword"];
//		$dwforcepass = $_POST["dwforcepass"];
		$periodofvalitystart = $_POST["periodofvalitystart"];
		$periodofvalityend = $_POST["periodofvalityend"];
//		$entrancevalitystart = $_POST["entrancevalitystart"];
//		$entrancevalityend = $_POST["entrancevalityend"];
//		$leavevalitystart = $_POST["leavevalitystart"];
//		$leavevalityend = $_POST["leavevalityend"];
/*		$jingruqishi1 = $_POST["jingruqishi1"];
		$jingrujieshu1 = $_POST["jingrujieshu1"];
		$likaiqishi1 = $_POST["likaiqishi1"];
		$likaijieshu1 = $_POST["likaijieshu1"];
		$jingruqishi2 = $_POST["jingruqishi2"];
		$jingrujieshu2 = $_POST["jingrujieshu2"];
		$likaiqishi2 = $_POST["likaiqishi2"];
		$likaijieshu2 = $_POST["likaijieshu2"];
		$jingruqishi3 = $_POST["jingruqishi3"];
		$jingrujieshu3 = $_POST["jingrujieshu3"];
		$likaiqishi3 = $_POST["likaiqishi3"];
		$likaijieshu3 = $_POST["likaijieshu3"];
		$jingruqishi4 = $_POST["jingruqishi4"];
		$jingrujieshu4 = $_POST["jingrujieshu4"];
		$likaiqishi4 = $_POST["likaiqishi4"];
		$likaijieshu4 = $_POST["likaijieshu4"];*/
		
		$staffgender = $_POST["staffgender"];
		$staffage = $_POST["staffage"];		
/*		$destination_folder = "pic/";
		$picfilename = $_POST["picfilename"];
		$pinfo=pathinfo($picfilename);  
		$picfilename = $destination_folder.$pinfo["basename"];*/

		$destination_folder = "zaopian/".$staffnum."/";
		$picfilename = $_POST["picfilename"];
		$pinfo=pathinfo($picfilename);
		$ftype=$pinfo['extension'];  
		$picfilename = $destination_folder.$staffnum.".".$ftype;

		@file_put_contents("test.log", "\n controlerNum: ".$controlerNum." add: ".$add." staffnum: ".$staffnum." staffname: ".$staffname." departmentname: ".$departmentname." periodofvalitystart: ".$periodofvalitystart." periodofvalityend: ".$periodofvalityend." staffgender: ".$staffgender." staffage: ".$staffage." picfilename: ".$picfilename." LINE: ".__LINE__."\n", FILE_APPEND);

		$myconn=dwopendb();
		if($controlerNum==='ALL')
		{					
			$strSql="select distinct controlerNum,lasttime from gatesetting WHERE controlerNum != 'ALL' ORDER BY lasttime DESC;";
			$result1=mysql_query($strSql,$myconn);
//			$result1=mysql_query($strSql);	
			while($dbResult1 = mysql_fetch_array($result1))
			{
//				@file_put_contents("test.log", "\n controlerNum: ".$dbResult1[0]." add: ".$add."\n", FILE_APPEND);
				if(!$auth && $add=="update")
				{
					if($staffsign=="0")
					{
//						$strSql="UPDATE staffbasesetting SET synstate= $staffauth,staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";
						$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',,staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";
//						$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',jingruqishi1='$jingruqishi1',jingrujieshu1='$jingrujieshu1',likaiqishi1='$likaiqishi1',likaijieshu1='$likaijieshu1',jingruqishi2='$jingruqishi2',jingrujieshu2='$jingrujieshu2',likaiqishi2='$likaiqishi2',likaijieshu2='$likaijieshu2',jingruqishi3='$jingruqishi3',jingrujieshu3='$jingrujieshu3',likaiqishi3='$likaiqishi3',likaijieshu3='$likaijieshu3',jingruqishi4='$jingruqishi4',jingrujieshu4='$jingrujieshu4',likaiqishi4='$likaiqishi4',likaijieshu4='$likaijieshu4',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";	
//						$msg="{\"dwdevice\":\"".$dbResult1[0]."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"departmentID\":\"".$departmentID."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//						dwsendtoserver($msg);
					}else
					{
//						$strSql="UPDATE staffbasesetting SET signature='$staffsign',synstate= $staffauth,staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';"; 
						$strSql="UPDATE staffbasesetting SET signature='$staffsign',staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',,staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";
//						$strSql="UPDATE staffbasesetting SET signature='$staffsign',staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',jingruqishi1='$jingruqishi1',jingrujieshu1='$jingrujieshu1',likaiqishi1='$likaiqishi1',likaijieshu1='$likaijieshu1',jingruqishi2='$jingruqishi2',jingrujieshu2='$jingrujieshu2',likaiqishi2='$likaiqishi2',likaijieshu2='$likaijieshu2',jingruqishi3='$jingruqishi3',jingrujieshu3='$jingrujieshu3',likaiqishi3='$likaiqishi3',likaijieshu3='$likaijieshu3',jingruqishi4='$jingruqishi4',jingrujieshu4='$jingrujieshu4',likaiqishi4='$likaiqishi4',likaijieshu4='$likaijieshu4',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";	
//						$msg="{\"dwdevice\":\"".$dbResult1[0]."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\"".$dwforcepass."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//						$msg="{\"dwdevice\":\"".$dbResult1[0]."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"departmentID\":\"".$departmentID."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//						dwsendtoserver($msg);
					}
					file_put_contents("test.log", "\n strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND);					
					$result=mysql_query($strSql,$myconn);
//					$dbResult = mysql_fetch_array($result);
//					mysql_free_result($result);				
//					if((mysql_affected_rows()==0) or (mysql_affected_rows==-1))
					$rvulae = dwsavepicfile($destination_folder,$picfilename,$url,$staffnum);
					if($result && !$rvulae)
					{
//						$myconn11=dwopendb();
				/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
						$result44=mysql_query($strSql,$myconn);
				//		$result=mysql_query($strSql);
						$dbResult44 = mysql_fetch_array($result44);
						if($dbResult44[0])
						{
							$TCPport = $dbResult44[0];
						}else
						{
							$TCPport = "1119";
						}
						mysql_free_result($result44);
//						dwclosedb($myconn11);
						dwsendtoserver($msg,$myconn11);*/
						echo "<script language=\"JavaScript\">alert('修改成功。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//						@file_put_contents("test.log", "\n 002 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
					}
					else
					{
						echo "<script language=\"JavaScript\">alert('修改失败。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//						@file_put_contents("test.log", "\n 003 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
					}
					mysql_free_result($result);					
				}else 
				{
					$strSql="select MAX(rowid) from staffbasesetting WHERE staffnum='$staffnum';";				
					$result=mysql_query($strSql,$myconn);
//					$result=mysql_query($strSql);
					$rowsnum = mysql_fetch_array($result);
//					@file_put_contents("test.log", "\n strSql: ".$strSql."\n", FILE_APPEND);
					mysql_free_result($result);
					if($rowsnum[0])
					{
						echo "<script language=\"JavaScript\">alert('人员编号重复。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//						@file_put_contents("test.log", "\n rowsnum[0]: ".$rowsnum[0]."\n", FILE_APPEND);
					}else
					{
						if($add=="update")
						{
//							$strSql="UPDATE staffbasesetting SET synstate= $staffauth,staffnum='$staffnum',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffname='$staffname';";
							$strSql="UPDATE staffbasesetting SET signature='$staffsign',staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',,staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';"; 
//							$strSql="UPDATE staffbasesetting SET signature='$staffsign',staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',jingruqishi1='$jingruqishi1',jingrujieshu1='$jingrujieshu1',likaiqishi1='$likaiqishi1',likaijieshu1='$likaijieshu1',jingruqishi2='$jingruqishi2',jingrujieshu2='$jingrujieshu2',likaiqishi2='$likaiqishi2',likaijieshu2='$likaijieshu2',jingruqishi3='$jingruqishi3',jingrujieshu3='$jingrujieshu3',likaiqishi3='$likaiqishi3',likaijieshu3='$likaijieshu3',jingruqishi4='$jingruqishi4',jingrujieshu4='$jingrujieshu4',likaiqishi4='$likaiqishi4',likaijieshu4='$likaijieshu4',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$dbResult1[0]' WHERE staffnum='$staffnum';";
//							$msg="{\"dwdevice\":\"".$dbResult1[0]."\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\""."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//							dwsendtoserver($msg);
						}else if($add=="add")
						{
							$strSql="insert into  staffbasesetting (staffnum,staffname,signature,cardnum, departmentname,departmentID,controlerNum,gatenum,staffgender,staffage,picfilename,periodofvalitystart,periodofvalityend) values ('$staffnum','$staffname','$staffsign','$cardnum','$departmentname','$departmentID','$dbResult1[0]','$gatenum','$staffgender',$staffage,'$picfilename','$periodofvalitystart','$periodofvalityend');";
//							$strSql="insert into  staffbasesetting (staffnum,staffname,signature,cardnum, departmentname,departmentID,controlerNum,gatenum,staffgender,staffage,picfilename,periodofvalitystart,periodofvalityend,jingruqishi1,jingrujieshu1,likaiqishi1,likaijieshu1,jingruqishi2,jingrujieshu2,likaiqishi2,likaijieshu2,jingruqishi3,jingrujieshu3,likaiqishi3,likaijieshu3,jingruqishi4,jingrujieshu4,likaiqishi4,likaijieshu4) values ('$staffnum','$staffname','$staffsign','$cardnum','$departmentname','$departmentID','$dbResult1[0]','$gatenum','$staffgender',$staffage,'$picfilename','$periodofvalitystart','$periodofvalityend','$jingruqishi1','$jingrujieshu1','$likaiqishi1','$likaijieshu1','$jingruqishi2','$jingrujieshu2','$likaiqishi2','$likaijieshu2','$jingruqishi3','$jingrujieshu3','$likaiqishi3','$likaijieshu3','$jingruqishi4','$jingrujieshu4','$likaiqishi4','$likaijieshu4');"; 					
//							$msg="{\"dwdevice\":\"".$dbResult1[0]."\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\""."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//							dwsendtoserver($msg);
							$staffnum = (int)$staffnum + 1;
						}
//						$msg="{\"dwdevice\":\"".$dbResult1[0]."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//						dwsendtoserver($msg);
						@file_put_contents("test.log", "\n strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND);
						$result=mysql_query($strSql,$myconn);						
//						$dbResult = mysql_fetch_array($result);
//						mysql_free_result($result);				
//						if($dbResult[0])
						$rvulae = dwsavepicfile($destination_folder,$picfilename,$url,$staffnum);
						if($result && !$rvulae)
						{
/*							$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
							$result44=mysql_query($strSql,$myconn);
					//		$result=mysql_query($strSql);
							$dbResult44 = mysql_fetch_array($result44);
							if($dbResult44[0])
							{
								$TCPport = $dbResult44[0];
							}else
							{
								$TCPport = "1119";
							}
							mysql_free_result($result44);
							dwsendtoserver($msg,$myconn);*/
							if($add=="update")
							{
								echo "<script language=\"JavaScript\">alert('授权成功。');</script><br/>";
//								@file_put_contents("test.log", "\n 004 sqlstr: ".$sqlstr."\n msg: ".$msg."\n", FILE_APPEND);
							}else if($add=="add")
							{
								echo "<script language=\"JavaScript\">alert('增加成功。');</script><br/>";
							}
//							echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//							@file_put_contents("test.log", "\n 004 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
						}
						else
						{
							if($add=="update")
							{
								echo "<script language=\"JavaScript\">alert('授权失败。');</script><br/>";
							}else if($add=="add")
							{
								echo "<script language=\"JavaScript\">alert('增加失败。');</script><br/>";
							}
						}
						mysql_free_result($result);	
					}				
				}
//				@file_put_contents("test.log", "\n 00 controlerNum: ".$dbResult1[0]." 01 controlerNum: ".$dbResult1[1]." add: ".$add."\n", FILE_APPEND);
			}
			mysql_free_result($result1);
		}else
		{
			if(!$auth && $add=="update")
			{
				if($staffsign=="0")
				{
//					$strSql="UPDATE staffbasesetting SET synstate= $staffauth,staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
					$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',,staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
//					$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',jingruqishi1='$jingruqishi1',jingrujieshu1='$jingrujieshu1',likaiqishi1='$likaiqishi1',likaijieshu1='$likaijieshu1',jingruqishi2='$jingruqishi2',jingrujieshu2='$jingrujieshu2',likaiqishi2='$likaiqishi2',likaijieshu2='$likaijieshu2',jingruqishi3='$jingruqishi3',jingrujieshu3='$jingrujieshu3',likaiqishi3='$likaiqishi3',likaijieshu3='$likaijieshu3',jingruqishi4='$jingruqishi4',jingrujieshu4='$jingrujieshu4',likaiqishi4='$likaiqishi4',likaijieshu4='$likaijieshu4',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
					
//					$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\"".$dwforcepass."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//					$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//					dwsendtoserver($msg);
				}else
				{
					$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
//					$strSql="UPDATE staffbasesetting SET signature='$staffsign',synstate= $staffauth,staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
//					$strSql="UPDATE staffbasesetting SET signature='$staffsign',synstate= $staffauth,staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',entrancevalitystart='$entrancevalitystart',entrancevalityend='$entrancevalityend',leavevalitystart='$leavevalitystart',leavevalityend='$leavevalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";

//					$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\"".$dwforcepass."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//					$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//					dwsendtoserver($msg);
				}
				@file_put_contents("test.log", "\n strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND);				
				$result=mysql_query($strSql);
//				$dbResult = mysql_fetch_array($result);
//				mysql_free_result($result);				
//				if($dbResult[0])
				$rvulae = dwsavepicfile($destination_folder,$picfilename,$url,$staffnum);
				if($result && !$rvulae)
				{
			/*		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
					$result44=mysql_query($strSql,$myconn);
			//		$result=mysql_query($strSql);
					$dbResult44 = mysql_fetch_array($result44);
					if($dbResult44[0])
					{
						$TCPport = $dbResult44[0];
					}else
					{
						$TCPport = "1119";
					}
					mysql_free_result($result44);
					dwsendtoserver($msg,$TCPport);*/
					echo "<script language=\"JavaScript\">alert('修改成功。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//					@file_put_contents("test.log", "\n 000 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
				}
				else
				{
					echo "<script language=\"JavaScript\">alert('修改失败。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
//					@file_put_contents("test.log", "\n 001 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
				}
			}else
			{
				$strSql="select MAX(skid) from staffbasesetting WHERE staffnum='$staffnum';";
				$result=mysql_query($strSql,$myconn);
//				$result=mysql_query($strSql);
				$rowsnum = mysql_fetch_array($result);
				mysql_free_result($result);
				if($rowsnum[0])
				{
					echo "<script language=\"JavaScript\">alert('人员编号重复。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
				}else
				{
					if($add=="update")
					{
//						$strSql="UPDATE staffbasesetting SET synstate= $staffauth,staffnum='$staffnum',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',dwpassword='$dwpassword',dwforcepass='$dwforcepass',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffname='$staffname';"; 
						$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',,staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
//						$strSql="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',departmentID='$departmentID',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',gatename='$gatename',jingruqishi1='$jingruqishi1',jingrujieshu1='$jingrujieshu1',likaiqishi1='$likaiqishi1',likaijieshu1='$likaijieshu1',jingruqishi2='$jingruqishi2',jingrujieshu2='$jingrujieshu2',likaiqishi2='$likaiqishi2',likaijieshu2='$likaijieshu2',jingruqishi3='$jingruqishi3',jingrujieshu3='$jingrujieshu3',likaiqishi3='$likaiqishi3',likaijieshu3='$likaijieshu3',jingruqishi4='$jingruqishi4',jingrujieshu4='$jingrujieshu4',likaiqishi4='$likaiqishi4',likaijieshu4='$likaijieshu4',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename',controlerNum='$controlerNum' WHERE staffnum='$staffnum';";
						@file_put_contents("test.log", "\n strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND);
//						$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\"".$dwforcepass."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";						
//						$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
					}else if($add=="add")
					{
//						$strSql="insert into staffbasesetting (signature,synstate,staffnum,staffname,cardnum,departmentname,gatename,controlerNum,gatenum,dwpassword,dwforcepass,periodofvalitystart,periodofvalityend,staffgender,staffage,picfilename) values ('$staffsign',$staffauth,'$staffnum','$staffname','$cardnum','$departmentname','$gatename','$controlerNum','$gatenum','$dwpassword','$dwforcepass','$periodofvalitystart','$periodofvalityend','$staffgender',$staffage,'$picfilename');"; 
						$strSql="insert into  staffbasesetting (staffnum,staffname,signature,cardnum, departmentname,departmentID,controlerNum,gatenum,staffgender,staffage,picfilename,periodofvalitystart,periodofvalityend) values ('$staffnum','$staffname','$staffsign','$cardnum','$departmentname','$departmentID','$controlerNum','$gatenum','$staffgender',$staffage,'$picfilename','$periodofvalitystart','$periodofvalityend');";
//						$strSql="insert into  staffbasesetting (staffnum,staffname,signature,cardnum, departmentname,departmentID,controlerNum,gatenum,staffgender,staffage,picfilename,periodofvalitystart,periodofvalityend,jingruqishi1,jingrujieshu1,likaiqishi1,likaijieshu1,jingruqishi2,jingrujieshu2,likaiqishi2,likaijieshu2,jingruqishi3,jingrujieshu3,likaiqishi3,likaijieshu3,jingruqishi4,jingrujieshu4,likaiqishi4,likaijieshu4) values ('$staffnum','$staffname','$staffsign','$cardnum','$departmentname','$departmentID','$controlerNum','$gatenum','$staffgender',$staffage,'$picfilename','$periodofvalitystart','$periodofvalityend','$jingruqishi1','$jingrujieshu1','$likaiqishi1','$likaijieshu1','$jingruqishi2','$jingrujieshu2','$likaiqishi2','$likaijieshu2','$jingruqishi3','$jingrujieshu3','$likaiqishi3','$likaijieshu3','$jingruqishi4','$jingrujieshu4','$likaiqishi4','$likaijieshu4');"; 
						@file_put_contents("test.log", "\n strSql: ".$strSql." LINE:".__LINE__."\n", FILE_APPEND);
//						$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"dwpassword\":\"".$dwpassword."\",\"dwforcepass\":\"".$dwforcepass."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"entrancevalitystart\":\"".$entrancevalitystart."\",\"entrancevalityend\":\"".$entrancevalityend."\",\"leavevalitystart\":\"".$leavevalitystart."\",\"leavevalityend\":\"".$leavevalityend."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";	
//						$msg="{\"dwdevice\":\"".$controlerNum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_UPDATE_USERINFO\",\"idcard\":\"".$cardnum."\",\"userid\":\"".$staffnum."\",\"staffsign\":\"".$staffsign."\",\"departmentname\":\"".$departmentname."\",\"name\":\"".$staffname."\",\"gatenumber\":\"".$gatenum."\",\"periodofvalitystart\":\"".$periodofvalitystart."\",\"periodofvalityend\":\"".$periodofvalityend."\",\"jingruqishi1\":\"".$jingruqishi1."\",\"jingrujieshu1\":\"".$jingrujieshu1."\",\"likaiqishi1\":\"".$likaiqishi1."\",\"likaijieshu1\":\"".$likaijieshu1."\",\"jingruqishi2\":\"".$jingruqishi2."\",\"jingrujieshu2\":\"".$jingrujieshu2."\",\"likaiqishi2\":\"".$likaiqishi2."\",\"likaijieshu2\":\"".$likaijieshu2."\",\"jingruqishi3\":\"".$jingruqishi3."\",\"jingrujieshu3\":\"".$jingrujieshu3."\",\"likaiqishi3\":\"".$likaiqishi3."\",\"likaijieshu3\":\"".$likaijieshu3."\",\"jingruqishi4\":\"".$jingruqishi4."\",\"jingrujieshu4\":\"".$jingrujieshu4."\",\"likaiqishi4\":\"".$likaiqishi4."\",\"likaijieshu4\":\"".$likaijieshu4."\",\"staffgender\":\"".$staffgender."\",\"staffage\":\"".$staffage."\",\"picfilename\":\"".$picfilename."\"}";
//						@file_put_contents("test.log", "\n msg: ".$msg."\n", FILE_APPEND);		
					}
					$result=mysql_query($strSql,$myconn);
//					$dbResult = mysql_fetch_array($result);
//					mysql_free_result($result);				
//					if($dbResult[0])
					$rvulae = dwsavepicfile($destination_folder,$picfilename,$url,$staffnum);
					if($result && !$rvulae)
					{
/*						$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
						$result44=mysql_query($strSql,$myconn);
				//		$result=mysql_query($strSql);
						$dbResult44 = mysql_fetch_array($result44);
						if($dbResult44[0])
						{
							$TCPport = $dbResult44[0];
						}else
						{
							$TCPport = "1119";
						}
						mysql_free_result($result44);
						dwsendtoserver($msg,$TCPport);*/
						if($add=="update")
						{
							echo "<script language=\"JavaScript\">alert('授权成功。');</script><br/>";
//							@file_put_contents("test.log", "\n 005 strSql: ".$strSql."\n msg: ".$msg."\n", FILE_APPEND);
						}else if($add=="add")
						{
							echo "<script language=\"JavaScript\">alert('增加成功。');</script><br/>";
						}
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";
					}
					else
					{
						if($add=="update")
						{
							echo "<script language=\"JavaScript\">alert('授权失败。');</script><br/>";
						}else if($add=="add")
						{
							echo "<script language=\"JavaScript\">alert('增加失败。');</script><br/>";
						}
					}
				}	
			}
//			mysql_free_result($result);						
		}
		dwclosedb($myconn);
/*		$max_file_size = 20000;
		$uptypes=array(  
		'image/jpg',  
		'image/jpeg',  
		'image/png',  
		'image/pjpeg',  
		'image/gif',  
		'image/bmp',  
		'image/x-png'  
		);  
		if (!is_uploaded_file($_FILES["filename"][tmp_name]))  
		//是否存在文件  
		{  
//			echo "<script language=\"JavaScript\">alert('图片不存在。');</script><br/>";
//			echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
		}else 
		{
			$file = $_FILES["filename"];  
			if($max_file_size < $file["size"])  
			//检查文件大小  
			{  
				echo "<script language=\"JavaScript\">alert('文件太大。');</script><br/>";
//				echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
			}else
			{		  
				if(!in_array($file["type"], $uptypes))  
				//检查文件类型  
				{  
					echo "<script language=\"JavaScript\">alert('\"文件类型不符。\"".$file["type"]."。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
				}else
				{
					if(!file_exists($destination_folder))  
					{  
						mkdir($destination_folder);  
					}  
				  
					$filename=$file["tmp_name"];  
					$image_size = getimagesize($filename);  
					$pinfo=pathinfo($file["name"]);  
					$real_filename = $pinfo["basename"];
					$ftype=$pinfo['extension'];  
					$destination = $destination_folder.$real_filename; 
					if (file_exists($destination) )  
					{  
						echo "<script language=\"JavaScript\">alert('同名文件已经存在了。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
					}  
				  
					if(!move_uploaded_file ($filename, $destination))  
					{  
						echo "<script language=\"JavaScript\">alert('移动文件出错。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
					}
				}
			}
		}*/
		echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='".$url."',5000);</script><br/>";	
	}
	
	function dwsendtoserver($msg,$myconn)
	{		
		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
		$result44=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$dbResult44 = mysql_fetch_array($result44);
		if($dbResult44[0])
		{
			$TCPport = $dbResult44[0];
		}else
		{
			$TCPport = "1119";
		}
		mysql_free_result($result44);
		if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false)
		{
//	        echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        $string = "socket_create() 1failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
			socket_clear_error();
//			socket_close($sock);
			return false;
        }else
		{
//		    echo "socket_create OK.<br/>";
//			$string = "socket_create() 2failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
		}
		if(socket_connect($sock, '127.0.0.1', $TCPport)===false)
		{
//		socket_bind($sock, '127.0.0.1', 0);
//			file_put_contents("test.log","\n socket_connect1: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
			socket_clear_error();
			socket_close($sock);
			return false;
		}
		if(socket_sendto($sock, $msg, strlen($msg),0,"127.0.0.1",$TCPport)===false)
		{
/*			    $err =  socket_strerror() ;
			echo "err:".$err.'<br/>';
			return array("Fault"=>$err);*/
//				file_put_contents("test.log","2 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"ERROR\"}";
			socket_clear_error();
			socket_close($sock);
			return false;
		}else
		{
//			    echo 'sendto client message:'.$msg3.'message len:'.strlen($msg3).'<br/>';
//				file_put_contents("test.log","3 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"OK\"}";
		}
		socket_clear_error();
		socket_close($sock);
		return true;
	}
	
	function dwclosedb($myconn)
	{
		mysql_close($myconn);	
	}
	
	function dwopendb()
	{
		$myconn=@mysql_connect("localhost","dw","DWdawu-309");
		if(!$myconn)
		{
//			die('Could not connect: '.mysql_error());
			$string = "Can't connect database : ".mysql_error()." LINE:".__LINE__."\n";
			file_put_contents("test.log", $string, FILE_APPEND);
			return false;
		}
		$db_selected=mysql_select_db("dwzuapairenlian",$myconn);
		if(!$db_selected)
		{
//			die("Can't use database dwaccessDB : ".mysql_error());       
			$strSql="CREATE DATABASE dwzuapairenlian;";
			$result=mysql_query($strSql,$myconn);
			if($result==false)
			{
				die("Can't use database dwaccessDB : ".mysql_error());
				$string = "Can't use database : ".mysql_error()." LINE:".__LINE__."\n";
				file_put_contents("test.log", $string, FILE_APPEND);
				dwclosedb($myconn);
				$response = base64_encode("{\"res\":\"deny3\"}");
				echo $response;					
				return false;
			}
			$strSql="set character_set_database=utf8;";
			$result=mysql_query($strSql,$myconn);
	
			mysql_close($myconn);
			return false;
		}
		return $myconn;
	}
	
    function uuid() 
	{
        if (function_exists('com_create_guid')) 
		{
            return md5(com_create_guid());
        }else 
		{
            mt_srand((double)microtime()*10000);                   //optional for php 4.2.0 and up.
            $charid = md5(uniqid(rand(),true)); 
//            $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); 
//            $hyphen = chr ( 45 );                                          // "-"
//            $uuid = '' .                                                   //chr(123)// "{"
//            substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );                                                                           //.chr(125);// "}"
            return $charid;
        }
    }

     //循环删除目录和文件函数
	function delDirAndFile( $dirName )
	{
//	    file_put_contents("test.log", "\n dirName: ".$dirName." LINE: ".__LINE__ ."\n", FILE_APPEND);
	    if ( $handle = opendir( "$dirName" ) ) 
	    {
	        while ( false !== ( $item = readdir( $handle ) ) ) 
	        {
	            if ( $item != "." && $item != ".." ) 
	            {
	                if ( is_dir( "$dirName/$item" ) ) 
	                {
	                    delDirAndFile( "$dirName/$item" );
	                } else 
	                {
	                    if( unlink( "$dirName/$item" ) )  
	                    {
//	                    	echo "成功删除文件： $dirName/$item \n";
	                    }
	                }
	            }
	        }
	        closedir( $handle );
	        if( rmdir( $dirName ) ) 
	        {
//	        	echo "成功删除目录： $dirName\n";
	        }
	    }
	}

/*    function delDirAndFile($path, $delDir = FALSE) 
    {
	    if (is_array($path)) 
	    {
	        foreach ($path as $subPath)
	            delDirAndFile($subPath, $delDir);
	    }
	    if (is_dir($path)) 
	    {
	        $handle = opendir($path);
	        if ($handle) 
	        {
	            while (false !== ( $item = readdir($handle) )) 
	            {
	                if ($item != "." && $item != "..")
	                    is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
	            }
	            closedir($handle);
	            if ($delDir)
	                return rmdir($path);
	        }
	    } else 
	    {
	        if (file_exists($path))
	         {
	            return unlink($path);
	        } else 
	        {
	            return FALSE;
	        }
	    }
	    clearstatcache();
	}*/
?>
